r - 将函数应用于来自不同列表的元素时出现问题
问题描述
我想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
关于我缺少什么的任何提示?
提前致谢。
解决方案
我想你只是混淆了[
和[[
。试试这个:
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)
推荐阅读
- javascript - 我不知道我在做什么错,我想在页面滚动时更改导航栏的背景颜色
- django - 产品详细信息的最佳模型字段?在 django 中
- amazon-web-services - 一个 Ec2 实例和一个 API 之间的 Ec2 代理
- python - 如何像计算机是全新的一样安装python包?
- mongodb - 为什么我的 Mongoose 填充请求不起作用?
- syntax - 序言中的规则与这些自然语言相协调
- java - 如何从数组列表中获取多语言 android 应用程序
- javascript - 承诺得到解决而不是被拒绝,甚至内部承诺也返回
- excel - 使用 Azure 数据工厂将多个 Excel 数据转换为一个主文件
- python - Django 实时作业