Reputation: 43
I have this data frame, in the column state
are the code number of a state,
I want to changes the code number for the real name of the state in a single line of code.
As you can see this method that I use is very long
data <- data.frame(state=c(1,2,3,4,5),
Population=c(4779736,710231,6392017,2915918,37253956))
data$state[data$state==1]<-"Alabama"
data$state[data$state==2]<-"Alaska"
data$state[data$state==3]<- "Arizona"
data$state[data$state==4]<- "Arkansas "
data$state[data$state==5]<-"California"
data
Upvotes: 0
Views: 178
Reputation: 887851
If the 'state' is numeric
with sequence values starting from 1, then create a vector
of state names in the same order as in the index and use the 'state' as index
data$state <- v1[data$state]
There is also state.name
which would give all the US states.
data$state <- state.name[data$state]
v1 <- c("Alabama", "Alaska", "Arizona", "Arkansas", "California")
Upvotes: 2