r - 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"
我的问题真的是:当将相同的代码复制到带有变量的命令行时,函数怎么会不起作用。
解决方案
您需要评估outcome
函数内部的参数,因此 R 会将其解释为变量,而不是文本
arranged <- arrange(dfout, State, eval(parse(text=outcome)), Hospital)
现在
# > best("TX","Heartattack")
# [1] CYPRESS FAIRBANKS MEDICAL CENTER
推荐阅读
- python - 发送带有 python 错误“连接意外关闭”的电子邮件
- java - 关于 ParallelStream 列表的潜在竞争条件的问题
- git - 在什么情况下 git 替换会被推/拉
- react-native - 自定义导航栏 - 不同场景下的不同图像
- typescript - 在命名空间扩充中使用模块中的类型
- angular - 按每个单词的第一个字母过滤包含元素的数组
- c# - 在nuget中设置复制到项目的文件的构建操作
- c# - 如何比较 f# 可区分联合实例的相等性?
- javascript - 在chart.js中具有时间刻度的数据开始和结束处的空白
- c - C 模运算符在我的代码中随机生成的整数表现异常