开发者

R: fragment a list

开发者 https://www.devze.com 2023-04-03 03:03 出处:网络
I am kind of tired of working with lists..and my limited R capabilities ... I could not solve this from long time...

I am kind of tired of working with lists..and my limited R capabilities ... I could not solve this from long time...

My list with multiple dataframe looks like the following:

set.seed(456)
sn1 = paste( "X", c(1:4), sep= "")
onelist <- list (df1 <- data.frame(sn = sn1, var1 = runif(4)),
         df2 <- data.frame(sn = sn1, var1 = runif(4)),
        df3 <- data.frame(sn = sn1,var1 = runif(4)))
[[1]]
  sn      var1
1 X1 0.3852362
2 X2 0.3729459
3开发者_开发百科 X3 0.2179086
4 X4 0.7551050

[[2]]
  sn      var1
1 X1 0.8216811
2 X2 0.5989182
3 X3 0.6510336
4 X4 0.8431172

[[3]]
  sn      var1
1 X1 0.4532381
2 X2 0.7167571
3 X3 0.2912222
4 X4 0.1798831

I want make a subset list in which the row 2 and 3 are only present.

   srow <-  c(2:3) # just I have many rows in real data 
    newlist <- lapply(onelist, function(y) subset(y, row(y) == srow))

The newlist is empty....

> newlist
[[1]]
[1] sn   var1
<0 rows> (or 0-length row.names)

[[2]]
[1] sn   var1
<0 rows> (or 0-length row.names)

[[3]]
[1] sn   var1
<0 rows> (or 0-length row.names)

Help please ....


Does this do it? Note the comma after the rows which implicitly is interpreted as NULL and results in the extraction all of the columns:

> lapply(onelist, "[", c(2,3),)
[[1]]
  sn      var1
2 X2 0.2105123
3 X3 0.7329553

[[2]]
  sn       var1
2 X2 0.33195997
3 X3 0.08243274

[[3]]
  sn      var1
2 X2 0.3852362
3 X3 0.3729459

You could have gotten your subset strategy to work with:

lapply(onelist, function(y) subset(y, rownames(y) %in% srow ))

Note that many time people use "==" when they really should be using %in%

?match


I don't think the row function does what you think it does:

Returns a matrix of integers indicating their row number in a matrix-like object, or a factor indicating the row labels.

Looking at what it returns on the list you have

> row(onelist[[1]])
     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
[4,]    4    4
> row(onelist[[1]])==srow
      [,1]  [,2]
[1,] FALSE FALSE
[2,] FALSE FALSE
[3,] FALSE FALSE
[4,] FALSE FALSE

You are doing a simple subset of the data.frames, so you can just use

newlist <- lapply(onelist, function(y) y[srow,])

which gives

> newlist
[[1]]
  sn      var1
2 X2 0.2105123
3 X3 0.7329553

[[2]]
  sn       var1
2 X2 0.33195997
3 X3 0.08243274

[[3]]
  sn      var1
2 X2 0.3852362
3 X3 0.3729459
0

精彩评论

暂无评论...
验证码 换一张
取 消