从列表中的两个数据框,我需要减去两列并得到另一个数据框
From two dataframes inside a list, I need to substract two columns and get another dataframe
我有这些数据框:
df1 <- data.frame( value=c(1,2,3,4), income= c(12,14,51,12))
df2 <- data.frame( value=c(2,3,4,7), income= c(14,11,53,13))
我需要获取这个数据框:
df3
value income
1 1 -12
2 2 0
3 3 -40
4 4 41
5 7 13
但是我使用了聚合函数,我得到了这个:
df3 <-do.call(rbind, l)%>% aggregate(income ~ value, ., FUN=diff)
value income
1 1 numeric(0)
2 2 0
3 3 -40
4 4 41
5 7 numeric(0)
感谢您的帮助
基础 R 答案。
df3 <- merge(df2, df1, by = "value", all = TRUE)
df3[is.na(df3)] <- 0
df3[["income"]] <- df3[["income.x"]] - df3[["income.y"]]
tidyverse 答案。
library("tidyverse")
df3 <- full_join(df1, df2, by = "value") %>%
replace_na(list(income.x = 0, income.y = 0)) %>%
mutate(income = income.x - income.y)
data.table回答。
library("data.table")
DT1 <- data.table(value=c(1,2,3,4), income= c(12,14,51,12))
DT2 <- data.table(value=c(2,3,4,7), income= c(14,11,53,13))
DT3 <- merge(DT1, DT2, by = "value", all = TRUE)
DT3[is.na(DT3)] <- 0
DT3[, income := income.x - income.y]
我有这些数据框:
df1 <- data.frame( value=c(1,2,3,4), income= c(12,14,51,12))
df2 <- data.frame( value=c(2,3,4,7), income= c(14,11,53,13))
我需要获取这个数据框:
df3
value income
1 1 -12
2 2 0
3 3 -40
4 4 41
5 7 13
但是我使用了聚合函数,我得到了这个:
df3 <-do.call(rbind, l)%>% aggregate(income ~ value, ., FUN=diff)
value income
1 1 numeric(0)
2 2 0
3 3 -40
4 4 41
5 7 numeric(0)
感谢您的帮助
基础 R 答案。
df3 <- merge(df2, df1, by = "value", all = TRUE)
df3[is.na(df3)] <- 0
df3[["income"]] <- df3[["income.x"]] - df3[["income.y"]]
tidyverse 答案。
library("tidyverse")
df3 <- full_join(df1, df2, by = "value") %>%
replace_na(list(income.x = 0, income.y = 0)) %>%
mutate(income = income.x - income.y)
data.table回答。
library("data.table")
DT1 <- data.table(value=c(1,2,3,4), income= c(12,14,51,12))
DT2 <- data.table(value=c(2,3,4,7), income= c(14,11,53,13))
DT3 <- merge(DT1, DT2, by = "value", all = TRUE)
DT3[is.na(DT3)] <- 0
DT3[, income := income.x - income.y]