简体   繁体   中英

Creating a new column of character values based on numeric value condition in R?

How do I create a new column of character values based on numeric value that are to be assigned the following names: 0 = user, 1 = admin, 2 = sponsor

dat1 
       one  two three
1     Bob    0  
2     Mary   0  
3 restaurant 2  
4   company  1  

so based on those names, how do I get to this:

dat1 
       one  two three
1     Bob    0  user
2     Mary   0  user
3 restaurant 2  sponsor
4   company  1  admin

dat1 <- data.frame(one=c("Bob", "Mary", "restaurant", "company"), two=c("0","0", "2", "1"))

And yes I know how simply create them via:

dat1 <- data.frame(one=c("Bob", "Mary", "restaurant", "company"), two=c("0","0", "2", "1"), three=c("user", "user", "sponsor", "admin"))

But what's the function that would preform the task? So under column three, based on the corresponding row under column two, I want 0 = user, 1 = admin, 2 = sponsor.

In your example, the two column is a factor. The integer representations of dat1$two as a factor are 1 for 0, 2 for 1, and 3 for 2. So if we use it as an index vector on a character vector of what we want to to get, we can expand the vector accordingly.

dat1$three <- c("user", "admin", "sponsor")[dat1$two]
dat1
#          one two   three
# 1        Bob   0    user
# 2       Mary   0    user
# 3 restaurant   2 sponsor
# 4    company   1   admin

If you don't already have a factor in the two column, you can make it into one with the following.

dat1$three <- c("user", "admin", "sponsor")[as.factor(dat1$two)]

These both create a new character column.

Update: As Frank mentions, the more idiomatic method would be to simply factor the two column and apply different labels.

dat1$three <- factor(dat1$two, labels = c("user", "admin", "sponsor"))

This creates a new factor column.

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