简体   繁体   中英

Subset from a list of data.frames

I have a list of data.frames. Suppose the list is composed by 10 data.frames. I would like first of all rename each list of data.frames according to a list of names stored in another file. Second, suppose the data.frames is named "Pippo" and "Pippo" is an element of the data.frame. I would like to subset in the following way:

Suppose this is the data.frame named "Pippo" from the list of data.frames:

 Name Sample1 Sample2 Sample3 Sample4 John 1 0 -3 -7 Michael 0 4 2 21 Pippo 1 1 23 0 

I would like to subset all the elements according to "Pippo" value == 1 so that the output will be:

 Name Sample1 Sample2 John 1 0 Michael 0 4 Pippo 1 1 

This will be done for all the names of the list of data.frames since each name is an element of the data.frame.

Let ldf be your list of dataframes. You can change the list's names using:

names(ldf) <- v

where v is a character vector.

For the second step (subsetting), this should work:

subset.ldf <- mapply(ldf, names(ldf),
                     function(x, name) x[, x[name, ] == 1, drop = FALSE])

Or a vector based solution:

d = data.frame(name=c('john','michael','pippo'), sample1 = c(1,0,1),
           sample2 = c(0,4,1), sample3 = c(-3,2,23), sample4 = c(-7,21,0))

sel = d[d$name == 'pippo',2:5]; sel = c(TRUE, sel == 1)
d[,sel]

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