从对象列表中排除元素

时间:2014-02-24 22:11:00

标签: r

我有一个元素列表

all<- list(a,b,c,d,e,f,g,h) 

列表包括对象和非现有元素(a是对象,b不存在)。

all
Error: objeto 'all' no encontrado

因为列表中的某些元素不存在。

我想找到一个表达式,从列表中排除非对象并获取仅包含那些存在的对象的列表。我尝试过表达式

exists(all)
Error en exists(all) : objeto 'all' no encontrado

谢谢

1 个答案:

答案 0 :(得分:1)

我认为这应该适合你。

LL <- as.character(substitute(c(a,b,c,d,e,f,g)))    #where a,b,c, etc are your objects
L2 <- LL[which(sapply(ll,exists))]    #checks to see if they exists
final_list <- sapply(L2,get)    #creates list of those objects that do exist

e.g。

a<-c(1,2,3)
b<-c('t','r','e')
d<-c('gfd','dgdf','gd')
f<-c(2,45,6)
l2<-as.character(substitute(c(a,b,c,d,e,f)))
> l2
[1] "c" "a" "b" "c" "d" "e" "f"
GOOD<-l2[which(sapply(l2,exists))]
> GOOD
[1] "c" "a" "b" "c" "d" "f"
sapply(GOOD,get)
$c
function (..., recursive = FALSE)  .Primitive("c")

$a
[1] 1 2 3

$b
[1] "t" "r" "e"

$c
function (..., recursive = FALSE)  .Primitive("c")

$d
[1] "gfd"  "dgdf" "gd"  

$f
[1]  2 45  6
相关问题