【发布时间】:2020-02-22 09:02:31
【问题描述】:
函数foo 强制subset 始终在任何子集中包含time 的所有值。
例如,如果我只想从 dat 中提取 prof == 1 子集,foo 也会将 time==1; time==2; time==3; time==4 添加到该子集。
但有时添加time 的一些值(在此示例中为time==1 和time==4)会导致subset 引发错误,因为此类子集没有数据。
我想知道如何在输出中过滤掉此类错误,即仅获取可能子设置的输出(此处为 time == 2 and 3)?
注意:数据是玩具,功能性解决方案值得赞赏。
# data.frame:
dat <- data.frame(time = c(1,3,2,4), prof = c(2,1,1,2))
# Function:
foo <- function(data, mod){
tim <- sort(unique(data$time))
s <- substitute(mod)
G <- lapply(tim, function(x) bquote(.(s) & time == .(x)))
lapply(1:length(G), function(i) subset(data, G[[i]]))
}
# EXAMPLE OF USE:
foo(dat, prof == 1) # Error in subset(data, G[[i]]) : 'subset' must be logical
# DESIRED OUTPUT:
[[1]]
time prof
1 2 1
[[2]]
time prof
1 3 1
【问题讨论】:
标签: r function loops dataframe subset