将功能应用于来自不同列表的元素时出现问题

时间:2019-07-15 20:01:11

标签: r mapply

我想使用两个列表中的元素来计算setdiff

为此,我创建了一个函数,当提供参数时,该函数可以正常工作,但是在尝试使用mapply时失败。

# The lists have the following structure
list_A <- list(
  vec_A1 = list(v1="1",v2="2",v3="3"),
  vec_A2 = list(v1="3",v2="4",v3="5")
  )

list_B <- list(
  mat_B1 = matrix(as.character(1:3),nrow = 3,ncol = 1),
  mat_B2 = matrix(as.character(3:5),nrow = 3,ncol = 1)  
)

myfun <- function(vec,mat){
  vec = unlist(vec) # Create a vector from the list's elements
  mat = mat[[1]] # Extract the required matrix
  x = apply(mat,1,base::setdiff,x=vec) %>% t # Compare the vector with each matrix row
  return(x)
}

# It gives my desired output when applied over single elements from the lists
myfun(list_A[1],list_B[1])
myfun(list_A[2],list_B[2])

# But fails when using mapply
mapply(myfun,list_A,list_B, SIMPLIFY = F)

所需的输出是

     [,1] [,2]
[1,] "2"  "3" 
[2,] "1"  "3" 
[3,] "1"  "2" 

     [,1] [,2]
[1,] "4"  "5" 
[2,] "3"  "5" 
[3,] "3"  "4" 

但是有了mapply我得到了

 Error in apply(mat, 1, base::setdiff, x = vec) : 
  dim(X) must have a positive length

关于我失踪的任何暗示吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

我认为您只是混淆了[[[。尝试以下方法:

myfun <- function(vec,mat){
    vec = unlist(vec) # Create a vector from the list's elements
    #mat = mat[[1]] # Extract the required matrix
    x = apply(mat,1,base::setdiff,x=vec) %>% t # Compare the vector with each matrix row
    return(x)
}

# It gives my desired output when applied over single elements from the lists
myfun(list_A[[1]],list_B[[1]])
myfun(list_A[[2]],list_B[[2]])

# But fails when using mapply
mapply(myfun,list_A,list_B, SIMPLIFY = F)