简体   繁体   English

替换 r 中两个数据帧之间的所有列值

[英]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 (eg 31 is Canada etc) is in a df with the number and Country.但是,由于调查,变量从显示参与者的国家/地区名称转换为数字,因此我下载了一个表格,其中国家/地区获得的代码(例如 31 是加拿大等)在带有数字和国家/地区的 df 中。 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).我想要的结果是 df1 中的 Country 变量从数字转换为国家名称(它们都是我数据集中的字符变量,包括国家数字,如果更好,可以转换为数字)。

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)]
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

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
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM