简体   繁体   中英

Extracting rows from a data.frame

I have an by m data.frame where column 1 has the information of interest. I want to create sub data.frame s 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

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

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

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM