0

I am having trouble to subset from a list using a variable of my function.

rankhospital <- function(state,outcome,num = "best") {

#code here

e3<-dataframe(...,state.name,...)


if (num=="worst"){ return(worst(state,outcome))
}else if((num%in%b=="TRUE" & outcome=="heart attack")=="TRUE"){
 sep<-split(e3,e3$state.name)
 hosp.estado<-sep$state
 hospital<-hosp.estado[num,1]
 return(as.character(hospital))

I split my data frame by state (which is a variable of my function) But hosp.estado<-sep$state doesn't work. I have also tried as.data.frame.

The function (rankhospital("NY"....) returns me a character(0).

When I feed the sep$state with sep$"NY" directly in code it works perfectly so I guess the problem is I can't use a function's variable to do this. Am I right? What could I use instead?

Thank you!!

2
  • 1
    Also, try sep[['state']]. Commented Jan 24, 2014 at 23:19
  • Also, your if-condition is needlessly complicated. num %in% b & outcome=="heart attack" would do just as well. Commented Jan 24, 2014 at 23:20

3 Answers 3

1

If state is a variable in your function, you can refer to a column with the name given by state using: sep[state] or sep[[state]]. The first produces a data frame with one column named based on the value of state. The second produces an unnamed vector.

df=data.frame(NY=rnorm(10),CA=rnorm(10), IL=rnorm(10))
state="NY"
df[state]
#             NY
# 1  -0.79533912
# 2  -0.05487747
# 3   0.25014132
# 4   0.61824329
# 5  -0.17262350
# 6  -2.22390027
# 7  -1.26361438
# 8   0.35872890
# 9  -0.01104548
# 10 -0.94064916
df[[state]]
#  [1] -0.79533912 -0.05487747  0.25014132  0.61824329 -0.17262350 -2.22390027 -1.26361438  0.35872890 -0.01104548 -0.94064916

class(df[state])
# [1] "data.frame"

class(df[[state]])
# [1] "numeric"
Sign up to request clarification or add additional context in comments.

Comments

0

It seems like you are trying to get the top hospital in a state. You don't want to split here (see the result of sep to see what I mean). Instead, use:

as.character(e3[e3$state.name==state, 1][num])

This hopefully does what you want.

Comments

0

You need sep[[state]] instead of sep$state to get the data frame out of your sep list, which matches the state parameter of your function. Like this:

e3 <- read.csv("https://raw.github.com/Hindol/data-analysis-coursera/master/HW3/hospital-data.csv")

state <- "WY"
num <- 1:5

sep<-split(e3,e3$State)
hosp.estado<-sep[[state]]
hospital<-hosp.estado[num,1]
as.character(hospital)
# [1] "530002" "530006" "530008" "530010" "530011"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.