我有2个数据框:
df1:
1 2 3 4 5
5 2 3 4 3
3 4 2 1
2 3 2
4 1
1
df2:
1 2 3 4 5
2 3 4 2 1
在这里,第一行“ 1、2、3、4、5”是两个数据框的列名
我要计算的Excel公式为:
=IF(A2="","",A2-$G2)
这里A是数据帧df1的第一个单元格,G2是数据帧df2的第一个单元格
Output:
3 2 -1 2 2
1 0 -2 -1
0 -1 -2
2 1
-1
如何在R中执行此操作?
可复制的示例:
df1 <- read.table(header=TRUE, stringsAsFactors=FALSE, row.names=1, text='
X1 X2 X3 X4 X5
1 5 2 3 4 3
2 3 4 2 1 NA
3 2 3 2 NA NA
4 4 1 NA NA NA
5 1 NA NA NA NA')
df2 <- read.table(header=TRUE, stringsAsFactors=FALSE, row.names=1, text='
X1 X2 X3 X4 X5
1 2 3 4 2 1')
答案 0 :(得分:2)
示例数据:(您未提供任何信息)
df1 <- mtcars[1:5,1:5]
# mpg cyl disp hp drat
# Mazda RX4 21.0 6 160 110 3.90
# Mazda RX4 Wag 21.0 6 160 110 3.90
# Datsun 710 22.8 4 108 93 3.85
# Hornet 4 Drive 21.4 6 258 110 3.08
# Hornet Sportabout 18.7 8 360 175 3.15
df2 <- mtcars[7,1:5]
# mpg cyl disp hp drat
# Duster 360 14.3 8 360 245 3.21
代码:
t(apply(df1,1,function(x){x - unlist(df2)}))
# mpg cyl disp hp drat
#Mazda RX4 6.7 -2 -200 -135 0.69
#Mazda RX4 Wag 6.7 -2 -200 -135 0.69
#Datsun 710 8.5 -4 -252 -152 0.64
#Hornet 4 Drive 7.1 -2 -102 -135 -0.13
#Hornet Sportabout 4.4 0 0 -70 -0.06
答案 1 :(得分:1)
使两个数据帧具有相同的暗淡(nrow和ncol),然后使用减法:
df1 - matrix(rep(unlist(df2), ncol(df2)), nrow = ncol(df2), byrow = TRUE)
# X1 X2 X3 X4 X5
# 1 3 -1 -1 2 2
# 2 1 1 -2 -1 NA
# 3 0 0 -2 NA NA
# 4 2 -2 NA NA NA
# 5 -1 NA NA NA NA
答案 2 :(得分:0)
data.frame(t(t(as.matrix(df1))-unlist((df2))))
X1 X2 X3 X4 X5
1 3 -1 -1 2 2
2 1 1 -2 -1 NA
3 0 0 -2 NA NA
4 2 -2 NA NA NA
5 -1 NA NA NA NA
sweep(df1,2,unlist(df2))
X1 X2 X3 X4 X5
1 3 -1 -1 2 2
2 1 1 -2 -1 NA
3 0 0 -2 NA NA
4 2 -2 NA NA NA
5 -1 NA NA NA NA