匹配行和减去列

时间:2013-08-06 10:08:05

标签: r subtraction

我有2个具有相同列和不同行数的数据集。

> dput(smalldf)
structure(list(X = structure(1:5, .Label = c("A", "B", "C", "F", 
"G"), class = "factor"), Y = c(1L, 2L, 3L, 6L, 7L), Z = c(10L, 
20L, 30L, 60L, 70L)), .Names = c("X", "Y", "Z"), class = "data.frame", row.names = c(NA, 
-5L))


> dput(bigdf)
structure(list(X = structure(1:7, .Label = c("A", "B", "C", "D", 
"E", "F", "G"), class = "factor"), Y = c(10L, 20L, 30L, 40L, 
50L, 60L, 70L), Z = c(100L, 200L, 300L, 400L, 500L, 600L, 700L
)), .Names = c("X", "Y", "Z"), class = "data.frame", row.names = c(NA, 
-7L))

我想匹配相似的行并减去Y列。我知道这是一项非常简单的任务,但我无法做到!我应该使用match()吗?或者某种apply()函数在这里?

1 个答案:

答案 0 :(得分:2)

这是一个常见的问题。在base R中执行此操作的一种方法是按照您的建议使用match,就像这样,看不到apply ....

#  rows of bigdf that appear in smalldf, in order that they appear in smalldf 
idx <- match( rownames(smalldf) , rownames(bigdf) ) 

#  subtract rows of smalldf from bigdf for rows that appear in smalldf and rbind them with original rows from bigdf that do not appear in samlldf
result <- rbind( ( bigdf[ idx , ] - smalldf ) , bigdf[ -idx , ] )

#  Order the results
result <- result[ order( rownames(result) ) , ]
   X  Y  Z
A  3  2  5
B 10  3  7
C  0  0  6
D  5  3  4
E  9 -2 20