首页 > 解决方案 > order() 参数长度中的错误不同 R

问题描述

我查看了所有关于 dplyr::arrange() 或 order() 参数长度不同错误的帖子,但没有找到解释。

我试图制作一个函数 best(),它可以从医院结果的数据帧 (dfout) 中返回最低额定值。当我将代码直接复制到 R 中时,它运行没有错误,返回死亡率最低的医院名称。只有当我将它作为函数调用时,它才会说“顺序错误(状态,结果,医院):参数长度不同”

函数:(注意我对 colnames 使用大写名称,对函数变量使用非大写名称)

best <- function(state, outcome){

colnames(dfout) <- c("Hospital", "State", "Heartattack", "Heartfailure", "Pneumonia")

##Return hospital name with lowest 30 day mortality rate

arranged <- arrange(dfout, State, outcome, Hospital)    ## arrange hospitals by state, mortality rate in the specified outcome in best() and alphabetically for the ties.
arranged1 <- arranged[arranged$State == state,]         ## take the part of the ordered list where state = the state specified in best()
arranged1$Hospital[1]

现在,如果我调用 best("TX", Heartattack) 我得到“顺序错误(状态,结果,医院):参数长度不同”,但如果我只是运行代码并将状态和结果替换为“TX”和 Heartattack 我去医院,像这样

##Return hospital name with lowest 30 day mortality rate

arranged <- arrange(dfout, State, Heartattack, Hospital)    ## arrange hospitals by state, mortality rate in the specified outcome in best() and alphabetically for the ties.
arranged1 <- arranged[arranged$State == "TX",]         ## take the part of the ordered list where state = the state specified in best()
arranged1$Hospital[1]
[1] "CYPRESS FAIRBANKS MEDICAL CENTER"

我的问题真的是:当将相同的代码复制到带有变量的命令行时,函数怎么会不起作用。

标签: r

解决方案


您需要评估outcome函数内部的参数,因此 R 会将其解释为变量,而不是文本

arranged <- arrange(dfout, State, eval(parse(text=outcome)), Hospital)

现在

   # > best("TX","Heartattack")
   # [1] CYPRESS FAIRBANKS MEDICAL CENTER

推荐阅读