1

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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.