0

I am very new to programming and am using R studio. I have 2 data frames: one containing a column "Animals" along with other data such as V1 (see df1), and another, shorter df which is a key for specifying a unique number for each animal type (see df2). Example:

df1 <- data.frame("V1"=c(33,45,21,78,45), "Animal"=c("Dog","Dog","Horse","Cat","Dog"))
df2 <- data.frame("Key"=c(1,2,3), "Animal"=c("Dog","Cat","Horse")

which look like this,

  V1 Animal
1 33    Dog
2 45    Dog
3 21  Horse
4 78    Cat
5 45    Dog

df2:
  Key Animal
1   1    Dog
2   2    Cat
3   3  Horse

Basically I would like to add a column to df1 specifying the number each animal type relates to and end up with something like this example:

df1
 V1 Animal Key
1 33    Dog 1
2 45    Dog 1
3 21  Horse 3
4 78    Cat 2
5 45    Dog 1

I tried this: df1 %>% mutate(total=ifelse(Animal==df2$Animal), df2$Key, as.character("NA"))

But got the error message below, partly I think because the 2 dfs have different number of rows.

Error in ifelse(Animal == df2$Animal) : 
  argument "yes" is missing, with no default
In addition: Warning messages:
1: In `==.default`(Animal, df2$Animal) :
  longer object length is not a multiple of shorter object length
2: In is.na(e1) | is.na(e2) :
  longer object length is not a multiple of shorter object length

Any help much appreciated, thanks!

Cat
  • 15
  • 4

3 Answers3

0

Does this work:

> df1$Key <- df2$Key[match(df1$Animal, df2$Animal)]
> df1
  V1 Animal Key
1 33    Dog   1
2 45    Dog   1
3 21  Horse   3
4 78    Cat   2
5 45    Dog   1
> 
Karthik S
  • 11,348
  • 2
  • 11
  • 25
0

Here's a dplyr solution with right_join, lots more details here if recognize this is a "join" or merge

library(dplyr)


right_join(df1, df2)
#> Joining, by = "Animal"
#>   V1 Animal Key
#> 1 33    Dog   1
#> 2 45    Dog   1
#> 3 21  Horse   3
#> 4 78    Cat   2
#> 5 45    Dog   1
Chuck P
  • 3,862
  • 3
  • 9
  • 20
0

A simple base R option is using merge

> merge(df1,df2)
  Animal V1 Key
1    Cat 78   2
2    Dog 33   1
3    Dog 45   1
4    Dog 45   1
5  Horse 21   3
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81