简体   繁体   中英

How to add a column in R using information from existing columns?

In my current data set, I have a column for state names and then a few other columns with some health information for each state. Basically I want to add a Region column that says which region each state is in. Here's what I've tried so far:

However, I get the error for the shorter object length not being a multiple of the longer object length. I know this means that there is differing length of each vector so it won't apply the argument. I'm essentially trying to say "if state name = one of the states in this item, apply the appropriate region to it". Any help is appreciated.

Try with %in% as == only checks for the first value in your vector:

#Code
cleandata$Region[cleandata$statename %in% south] <- "South"
cleandata$Region[cleandata$statename %in% midwest] <- "Midwest"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM