如何向R中的数据框添加另一列,以显示其他两个数据框的列之间的差异?

时间:2018-01-29 16:59:33

标签: r tidyr

我拥有的内容:

我有两个数据帧可供使用。那些是:

> print(myDF_2003)
  A_score country B_score
1     200 Germany      11
2     150   Italy       9
3       0  Sweden       0

> print(myDF_2005)
  A_score country B_score
1    -300  France      16
2     100 Germany      12
3     200   Italy      15
4      40   Spain      17

它们由以下代码生成,我不想更改:

#_________2003______________

myDF_2003=data.frame(c(200,150,0),c("Germany", "Italy", "Sweden"), c(11,9,0))
colnames(myDF_2003)=c("A_score","country", "B_score")

myDF_2003$country=as.character(myDF_2003$country)
myDF_2003$country=factor(myDF_2003$country, levels=unique(myDF_2003$country))

myDF_2003$A_score=as.numeric(as.character(myDF_2003$A_score))
myDF_2003$B_score=as.numeric(as.character(myDF_2003$B_score))

#_________2005______________

myDF_2005=data.frame(c(-300,100,200,40),c("France","Germany", "Italy", "Spain"), c(16,12,15,17))
colnames(myDF_2005)=c("A_score","country", "B_score")

myDF_2005$country=as.character(myDF_2005$country)
myDF_2005$country=factor(myDF_2005$country, levels=unique(myDF_2005$country))

myDF_2005$A_score=as.numeric(as.character(myDF_2005$A_score))
myDF_2005$B_score=as.numeric(as.character(myDF_2005$B_score))

我想要的是什么: 我想将另一列粘贴到myDF_2005,该列与之前两个数据框中存在的国家/地区的B_Scores不同。换句话说:我想产生这个输出:

> print(myDF_2005_2003_Diff)
      A_score country B_score B_score_Diff
    1    -300  France      16         
    2     100 Germany      12            1
    3     200   Italy      15            6
    4      40   Spain      17

问题: 这是最优雅的代码是什么?

2 个答案:

答案 0 :(得分:3)

# join in a temporary dataframe
temp <- merge(myDF_2005, myDF_2003, by = "country", all.x = T)
# calculate the difference and assign a new column
myDF_2005$B_score_Diff <- temp$B_score.x - temp$B_score.y

答案 1 :(得分:1)

使用的解决方案。我们的想法是合并两个数据框,然后计算差异。

library(dplyr)

myDF_2005_2 <- myDF_2005 %>%
  left_join(myDF_2003 %>% select(-A_score), by = "country") %>%
  mutate(B_score_Diff = B_score.x - B_score.y) %>%
  select(-B_score.y) %>%
  rename(B_score = B_score.x)
myDF_2005_2
#   A_score country B_score B_score_Diff
# 1    -300  France      16           NA
# 2     100 Germany      12            1
# 3     200   Italy      15            6
# 4      40   Spain      17           NA