我有以下数据框:df1
和df2
。如何减去列名相同的两个数据集(df1 - df2
)?
df1 <- read.table(header = TRUE, text = "
a b c
2 4 1
3 3 12
5 3 2")
df2 <- read.table(header = TRUE, text = "
c a b
0 1 7
4 1 8
3 2 9")
结果数据框df3
df3
a b c
1 -3 1
2 -5 8
3 -6 -1
答案 0 :(得分:3)
只需写下
df1-df2[colnames(df1)]
# a b c
# 1 1 -3 1
# 2 2 -5 8
# 3 3 -6 -1