提取列表元素

时间:2017-03-22 17:22:27

标签: r

我有一个列表,其中所有向量具有相同的长度,例如

tmp<-list(1:10, -5:5, 3:13)
names(tmp)<-c("a","b","c")

我想提取tmp的元素tmp$a == 1,即所需的输出应该相当于

output<-list(1,-5,3)
names(output)<-c("a","b","c")

受MATLAB的启发,我尝试使用tmp[tmp[["a"]] == 1, ],但这产生了错误。为什么这样做以及这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

Is seems you are basically describing a data.frame without using one. First, your example does not have equal length vectors, but this does:

tmp <- list(a=1:11, b=-5:5, c=3:13)

If we convert this to a data.frame, we can use subset()

subset(data.frame(tmp), a==1)
#   a  b c
# 1 1 -5 3

data.frames are basically just lists were all elements are vectors of equal length.

Otherwise @joran's answer still stands. You can apply the indexing operator over each vector in the list

lapply(tmp, "[[", which(tmp$a == 1))