-1

我有 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()功能?

4

1 回答 1

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
于 2013-08-06T10:30:14.740 回答