MCP_infiltrator
MCP_infiltrator

Reputation: 4179

Extracting rows from a data.frame

I have a n by m data.frame where column 1 has the information of interest. I want to create sub data.frames based upon what the value in a row of column 1 is.

Example:

P Cat  Q    S... nth Column
S data data data data 
S ...       ...       
A ...
I ...
. ...
. ...
. ...
mth row

Now what I want to do is create a data.frame where column P has a value of S, then one for A...,etc.

I have been unsuccessfully trying things such as:

s <- data.frame(df1$P = S)
s <- data.frame(df1$P [,:5]) <- #In this case the data I want stops at row 5

I would like to end up with something like

s = P Data1 Data2 Data3 Data nth
    S
    S
    ...
    S

Thank You

Upvotes: 3

Views: 2724

Answers (2)

thelatemail
thelatemail

Reputation: 93813

Breaking your data into a list of data.frames using split may also work here, and prevent cluttering your workspace. E.g:

df1 <- data.frame(P=c("S","S","A","I"),data=rep(1,4))
df1

#  P data
#1 S    1
#2 S    1
#3 A    1
#4 I    1

result <- split(df1,df1$P)

#$A
#  P data
#3 A    1
#
#$I
#  P data
#4 I    1
#
#$S
#  P data
#1 S    1
#2 S    1

You can then access the parts of the list like:

result$S

or

result[["S"]]

Voila:

#  P data
#1 S    1
#2 S    1

Upvotes: 1

screechOwl
screechOwl

Reputation: 28149

Instead of :

s <- data.frame(df1$P = S)

try:

s <- data.frame(df1[df1$P == S,])

or

s <- data.frame(df1[df1$P == 'S',])

if you want to control number of rows try:

s <- data.frame(df1[df1$P == 'S',1:5])

Upvotes: 0

Related Questions