使用mapply时出错:"' dimnames' [2]不等于数组范围"

时间:2017-12-21 09:54:00

标签: r mapply

在R中,当我尝试在下面的数据中使用列出的公式时,我得到一个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

1 个答案:

答案 0 :(得分:0)

错误基于'组织'数据中,的{​​{1}},导致使用"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"    

更新

根据OP的澄清,如果存在不匹配,那么我们需要有一个条件来确保它返回unlist(do.call(Map, c(f= choice, unname(Students))))

FALSE