R 将函数应用于不同列表中的元素时出现问题

R 将函数应用于不同列表中的元素时出现问题,r,mapply,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.ch

我想使用两个列表中的元素计算
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)
但是有了mapply我就明白了

 Error in apply(mat, 1, base::setdiff, x = vec) : 
  dim(X) must have a positive length
有没有关于我遗漏什么的线索


提前谢谢。

我想你把
[
[[
搞混了。试试这个:

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)

myfun删除
mat=mat[[1]]
并在直接调用函数时使用
[
而不是
[
调用元素上的函数。
myfun(list_A[1],list_B[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)