【发布时间】:2021-03-23 16:20:44
【问题描述】:
我想知道如何修改我的 mapply 调用以避免在我的最后一行代码之后得到:Error: $ operator is invalid for atomic vectors?
注意:使用matrix(c(1, .1, 2, .2), nrow = 2) 只是为了简单。
我的预期输出是:
$Trus
[,1] [,2]
[1,] 1.0 2.0
[2,] 0.1 0.2
$Yu_Chen
[,1] [,2]
[1,] 1.0 2.0
[2,] 0.1 0.2
我的可重现代码是:
ctlist <- function(mm, cont=FALSE, pos=1, outcom=1){
mm <- mm[[1]]
mm[mm$control==cont & mm$post == pos & mm$outcome == outcom, , drop = FALSE]
}
#=========
dinter <- function(m, pos, outcom){
clist <- ctlist(mm=m, cont=TRUE, pos = pos, outcom = outcom)
tlist <- ctlist(mm=m, cont=FALSE, pos = pos, outcom = outcom)
matrix(c(1, .1, 2, .2), nrow = 2) # For simplicity
}
#=========
L1 = list(Trus = data.frame(control=c(T,F), post=c(1,1), outcome=c(1,1), time=c(2,2)),
Yu_Chen = data.frame(control=c(F,F,T,T), post=c(1,2,1,2), outcome=c(1,1,1,1), time=c(1,2,1,2)) )
#=========
G <- function(m){
input <- rev(expand.grid(outcom = seq_len(max(m$outcom, na.rm = TRUE)), pos = seq_len(max(m$post, na.rm = TRUE))))
mapply(dinter, m=m, input$pos, input$outcom)
}
#=========
setNames(lapply(L1, G), names(L1))
#Error: $ operator is invalid for atomic vectors
#Called from: ctlist(mm = m, cont = TRUE, pos = pos, outcom = outcom)
【问题讨论】:
-
创建
mm <- mm[[1]]后问题会出现在mm$control -
根据你定义函数的方式,即'dinter',我不确定为什么需要
mapply/Map
标签: r function dataframe loops mapply