R:如何在列表中对data.frame进行子集化并返回data.frame?

时间:2011-08-04 13:09:13

标签: r dataframe subset

在列表中对data.frame进行子集化时,我得到向量而不是data.frames(参见下面的示例)。如何避免这种情况并获取data.frames?

l <- list(data.frame(a=c(1,2,3)), data.frame(b=c(4,5,6,5)), data.frame(c=c(3,4,5,6)))
names(l) <- c("A", "B", "C")
l
lapply(l, function(x) x[2:nrow(x), ])

输出

> l <- list(data.frame(a=c(1,2,3)), data.frame(b=c(4,5,6,5)), data.frame(c=c(3,4,5,6)))
> names(l) <- c("A", "B", "C")
> l
$A
  a
1 1
2 2
3 3

$B
  b
1 4
2 5
3 6
4 5

$C
  c
1 3
2 4
3 5
4 6

> lapply(l, function(x) x[2:nrow(x), ])
$A
[1] 2 3

$B
[1] 5 6 5

$C
[1] 4 5 6

1 个答案:

答案 0 :(得分:9)

你需要,drop = FALSE参数

> res <- lapply(l, function(x) x[2:nrow(x),, drop=FALSE])
> sapply(res,class)
           A            B            C 
"data.frame" "data.frame" "data.frame" 
> res
$A
  a
2 2
3 3

$B
  b
2 5
3 6
4 5

$C
  c
2 4
3 5
4 6
相关问题