我在R中创建多步函数时遇到问题。当我在函数外使用它们并将代码插入到代码行中时,我的代码行会起作用,但是当我使用function()并将变量插入到代码行,它通常是错误{'New York (NY)', 'United States (US)'}
例如,这是我现在正在使用的功能:
Error: Result must have length 370, not 0
我创建的所有函数都一遍又一遍地遇到这个问题。有什么建议吗?
best <- function(state, outcome) {
stateuse <- hospitaloutcome %>% filter(State == state)
stateusecols <- stateuse[,c(2,7,11,17,23)]
stateusecols <- stateusecols %>% rename('heart attack' =
'Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack')
stateusecols <- stateusecols %>% rename('heart failure' =
'Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure')
stateusecols <- stateusecols %>% rename('pneumonia' =
'Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia')
stateusecols$'heart failure' <- as.numeric(stateusecols$'heart failure')
stateusecols$'pneumonia' <- as.numeric(stateusecols$'pneumonia')
value <- min(stateusecols$outcome , na.rm=TRUE)
neededrow <- stateusecols %>% filter(stateusecols$outcome == value)
hospital <- neededrow[,1]
hospital
}
#But when I call best('TX','heart attack') it errors with the result must have length 370, not 0
#However when I just do this:
stateuse <- hospitaloutcome %>% filter(State == 'TX')
stateusecols <- stateuse[,c(2,7,11,17,23)]
stateusecols <- stateusecols %>% rename('heart attack' =
'Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack')
stateusecols <- stateusecols %>% rename('heart failure' =
'Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure')
stateusecols <- stateusecols %>% rename('pneumonia' =
'Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia')
stateusecols$'heart failure' <- as.numeric(stateusecols$'heart failure')
stateusecols$'pneumonia' <- as.numeric(stateusecols$'pneumonia')
value <- min(stateusecols$'heart attack' , na.rm=TRUE)
neededrow <- stateusecols %>% filter(stateusecols$'heart attack' == value)
hospital <- neededrow[,1]
hospital
#I get my answer, same lines of code, without the function() and the variables I need are in the same
#spots as the variables defined.
答案 0 :(得分:0)
@ user2554330的解决方案
通过将$outcome
的所有[,outcome,drop=TRUE]
换出,该功能现在可以使用了。
谢谢!