使用mapply时出错:“'dimnames'[2]的长度不等于数组范围”

问题描述 投票:0回答:1

在R中,当我尝试在下面的数据上使用列出的公式mapply时,我得到一个dimnames错误。我已经查看了这个dimnames错误的其他响应,但没有找到任何有用的解决方案。任何帮助将非常感激。

organizations <- data.frame(
  orgs = c("org1","org2","org,3"), 
  num_count = c(8,4,2), 
  position = c("position1", "position2", "position1"),
  stringsAsFactors=FALSE
  )

students <- data.frame(
  first_choice = c("org1", "org3", "org2", "org2"),
  role = c("position1", "position1", "position2", "position2"),
  id = c(2, 3, 9, 4),
  stringsAsFactors=FALSE
  )


choice<-function(x,y,z){
  ifelse(z<=subset(organizations, orgs==x & position==y, num_count), x  , "2nd Choice")
}
students$org <-mapply(choice,Students$first_choice,atudents$role,atudents$id)

错误看起来像:

 Error in matrix(unlist(value, recursive = FALSE, use.names = FALSE), nrow = nr,  : 
  length of 'dimnames' [2] not equal to array extent

.

r mapply
1个回答
0
投票

该错误基于,中“"org,3"”的“组织”数据,导致使用==进行不匹配。即如果我们看下面

Map(function(x, y, z) subset(organizations, Orgs == x& position == y, 
           num_count),Students$first_choice,Students$role,Students$id)
#$org1
#  num_count
#1         8

#$org3
#[1] num_count
#<0 rows> (or 0-length row.names)  #### no match

#$org2
#  num_count
#2         4

#$org2
#  num_count
#2         4

一旦纠正,它将正常工作

Students$org<- mapply(choice,Students$first_choice,Students$role,Students$id)
Students$org
#[1] "org1"       "2nd Choice" "2nd Choice" "org2"    

其他选择是

unlist(do.call(Map, c(f= choice, unname(Students))))

Update

根据OP的澄清,如果存在不匹配,那么我们需要有一个条件来确保它返回FALSE

unlist(Map(function(x, y, z) {
      x1 <- subset(organizations, Orgs == x& position == y, num_count)[,1]
    if(length(x1) > 0 && z <= x1) x else "2nd Choice"
    },
    Students$first_choice,Students$role,Students$id))
© www.soinside.com 2019 - 2024. All rights reserved.