R:如何在列表中对数据集进行子集并返回data.frame? [英] R: how to subset a data.frame in a list and return data.frame?
本文介绍了R:如何在列表中对数据集进行子集并返回data.frame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当将列表中的数据框架子集时,我将获取向量而不是data.frames(参见下面的示例)。如何避免这种情况并获取一个data.frames?
l< - list(data.frame(a = c ,2,3)),data.frame(b = c(4,5,6,5)),data.frame(c = c(3,4,5,6)))
名称(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)))
>名称(l)< - c(A,B,C)
> l
$ A
a
1 1
2 2
3 3
$ bb
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
解决方案
您需要,drop = FALSE参数
> res< - lapply(l,function(x)x [2:nrow(x),, drop = FALSE])
pre>
> sapply(res,class)
A B C
data.framedata.framedata.frame
> res
$ A
a
2 2
3 3
$ bb
2 5
3 6
4 5
$ C
c
2 4
3 5
4 6
When subsetting a data.frame inside of a list, I get vectors instead of a data.frames (see the example below). How to avoid this and get a 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), ])
output
> 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
解决方案You need the ,drop=FALSE argument
> 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
这篇关于R:如何在列表中对数据集进行子集并返回data.frame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文