best<-function(state,outcome){
data <- read.csv("outcome-of-care-measures.csv")
filter<-data.frame(cbind(data[, 2], # hospital
data[, 7], # state
data[, 11], # heart attack
data[, 17], # heart failure
data[, 23]), # pneumonia
stringsAsFactors = FALSE)
chosenState<-state
colnames(filter) <- c("Hospital", "State", "heart attack", "heart failure", "pneumonia")
if(!chosenState %in% filter[["State"]]){
stop('invalid state')
}
The above code is the initial code. It is converting state values to numeric hence values are like 1,2,3... Now if I write colClasses="character" in read.csv then this conversion stops and I get column values as characters. Why is that so? Final code below-->
best<-function(state,outcome){
data <- read.csv("outcome-of-care-measures.csv",colClasses = "character")
filter<-data.frame(cbind(data[, 2], # hospital
data[, 7], # state
data[, 11], # heart attack
data[, 17], # heart failure
data[, 23]), # pneumonia
stringsAsFactors = FALSE)
chosenState<-state
colnames(filter) <- c("Hospital", "State", "heart attack", "heart failure", "pneumonia")
if(!chosenState %in% filter[["State"]]){
stop('invalid state')
}
colClasses="character"
your states are being read in as factors duringread.csv
(that is unless you are using >R 4.0 where this behavior changed.) Then when you do all the cbind stuff on column vectors you are creating a matrix which makes everything numeric. There's no a good reason tocbind()
before passing todata.frame
. That step is the one that's triggering the data conversion. Not sure where that practice comes from but a lot of people seem to do it and it causes a lot of problems. – MrFlickdata.frame(cbind(...))
? I've never tried to track down the course materials. Also don't they have their own chat boards? I thought they used to discourage using SO for homework. – MrFlickdata.frame(cbind(...))
. I have all the course materials because have served as a Community Mentor for the curriculum. The guidance from JHU regarding SO is a bit ambivalent. On one hand, the Coursera Honor Code states that students must submit their own work. On the other hand, the professors (Roger Peng, Brian Caffo, and Jeff Leek) are big on the "hacker mentality", so much so that it frustrates the students that I had to write a blog article to address the topic. – Len Greski