【发布时间】:2016-09-16 09:49:28
【问题描述】:
我有一个 data.frame,其中一列是一个列表(参见 post)我想检查 data.frame 中的哪些列表包含一个元素(比如说数字 3)目前,我正在循环通过data.frame的所有行。
df=data.frame(a=1:3,b=I(list(1,3:7,1:3)))
df
for(i in 1:nrow(df)){
print(3 %in% df$b[[i]])
}
有没有更优雅的方式?
【问题讨论】:
-
你可以使用
apply(df, 1, function(x) 3 %in% unlist(x[2]))也可以循环,但也许是“优雅的”。 -
我会选择
mapply(`%in%`, 3, df$b)或sapply(df$b, function(x) 3 %in% x)或类似的东西 -
那肯定更优雅。我之前没有使用过
mapply。非常好。 -
如果您有一个可行的解决方案,但想知道什么会更好,那么这是 Code Review 而不是 StackOverflow 的问题。