Aite97
Aite97

Reputation: 165

Replacing all column values between two dataframes in r

I have two dataframes. One contains observations on a subject I'm studying. However, due to the surveying a variable was converted from displaying countryname of participant to a number, and so I downloaded a table where the code the country got (e.g. 31 is Canada etc) is in a df with the number and Country. I want to replace the numbers in the original dataframe with the countries from the second dataframe, but I fail every time.

Here I use an example dataframe:

df1 <- data.frame(list(Country=c("1","3","4","2"), Obs=c("Stuff1","Stuff2","Stuff3","Stuff4")))
df2 <- data.frame(list(Number=c("1","2","3","4"), Country=c("C1","C2","C3","C4")))

The result I want is that the Country variable in df1 is converted from the numbers to the country names (they are all character variables in my dataset including country numbers, can convert to numeric if it is better).

I have so far failed after trying the following:

df1 <- df1 %>% 
  mutate_at(c("Country"), funs(recode(.,'df1[,1]'=df2[,2])))

and

df1$newcountry <- data$Country[match(df1$Country, df2$Country)]

Upvotes: 0

Views: 34

Answers (2)

W. Joel Schneider
W. Joel Schneider

Reputation: 1806

library(tidyverse)
df1 <- data.frame(list(Country=c("1","3","4","2"), 
                       Obs=c("Stuff1","Stuff2","Stuff3","Stuff4")))
df2 <- data.frame(list(Number=c("1","2","3","4"), 
                       Country=c("C1","C2","C3","C4")))

df1 %>% rename(Number = Country) %>% 
  left_join(df2, by = "Number")
  Number    Obs Country
1      1 Stuff1      C1
2      3 Stuff2      C3
3      4 Stuff3      C4
4      2 Stuff4      C2

Upvotes: 1

Karthik S
Karthik S

Reputation: 11584

Does this work:

library(dplyr)
df1 %>% inner_join(df2, by = c('Country' = 'Number')) %>% 
rename(N = Country, Country = Country.y) %>% select(-1)
     Obs Country
1 Stuff1      C1
2 Stuff2      C3
3 Stuff3      C4
4 Stuff4      C2
 

Upvotes: 0

Related Questions