user3443063
user3443063

Reputation: 1615

R How can I replace values with values of another dataframe?

I have a huge dataframe df containing Numbers in the column "a" I also have a dataFrame name that contains the names corresponding to these numbers.

df:                          
 a   b     c                   name:
 1   val1  val2                  1  cat
 1   val1  val2                  2  dog
 2   val1  val2                  3  rabbit
 3   val1  val2
 3   val1  val2
 3   val1  val2

Now I want to replace the numbers with the names. The new dataFrame should look like this:

df:                                      
   a        b     c      
   cat      val1  val2                  
   cat      val1  val2                  
   dog      val1  val2                  
   rabbit   val1  val2
   rabbit   val1  val2
   rabbit   val1  val2

I realized this like that. It works but I am not content, because I hardCode the names ...

  df$a<-replace(df$a, df$a==1, "cat" )
  df$a<-replace(df$a, df$a==2, "dog" )
  df$a<-replace(df$a, df$a==3, "rabbit" )

How can I get the new values out of my dataframe name ?

Thank you!

Upvotes: 2

Views: 5666

Answers (3)

manotheshark
manotheshark

Reputation: 4357

This is merging the two data.frames. This does not require hard coding any values, but only adding new values to the data.frames

df <- data.frame(a = c(1,1,2,3,3,3), b = "val1", c = "val2")
df.name <- data.frame(a = 1:3, name=c("cat", "dog", "rabbit"))

df1 <- merge(df, df.name, by = "a")  # merge two data.frames by `a`

Some cleanup is required if you want the name to be stored in column a

df1$a <- df1$name
df1$name <- NULL

       a    b    c
1    cat val1 val2
2    cat val1 val2
3    dog val1 val2
4 rabbit val1 val2
5 rabbit val1 val2
6 rabbit val1 val2

Upvotes: 2

lampros
lampros

Reputation: 581

data:

df = data.frame(a = c(1,1,2,3,3,3), b = rep('val1', 6), c = rep('val2', 6))

replace values with characters:

df$a = c('cat', 'dog', 'rabbit')[ match(df$a, sort(unique(df$a))) ]

output

df
#       a    b    c
#1    cat val1 val2
#2    cat val1 val2
#3    dog val1 val2
#4 rabbit val1 val2
#5 rabbit val1 val2
#6 rabbit val1 val2

Upvotes: 2

Prradep
Prradep

Reputation: 5696

sample data:

df = data.frame(a = c(1,1,2,3,3,3), b = rep('val1', 6), c = rep('val2', 6))
df

#   a    b    c
# 1 1 val1 val2
# 2 1 val1 val2
# 3 2 val1 val2
# 4 3 val1 val2
# 5 3 val1 val2
# 6 3 val1 val2

using dplyr's recode(), you can achieve this:

df %>% mutate(a = recode(a, '1' = 'cat', '2' = 'dog', '3' = 'rabbit'))

#        a    b    c
# 1    cat val1 val2
# 2    cat val1 val2
# 3    dog val1 val2
# 4 rabbit val1 val2
# 5 rabbit val1 val2
# 6 rabbit val1 val2

Upvotes: 1

Related Questions