如何根据另一个数据框中的列对数据框进行子集化?

时间:2018-05-25 23:37:41

标签: r dataframe subset

我有两个数据框(df1df2),我想基于df1中包含的前两列来对df2进行子集化。例如,

df1 = data.frame(x=c(1,1,1,1,1),y=c(1,2,3,4,5),value=c(3,4,5,6,7))
df2 = data.frame(x=c(1,1,1,1,1,2), y=c(5,3,4,2,1,6), value=c(8,9,10,11,12,13))

enter image description here

正如我们所看到的,(2,6)中的第6行df2未包含在df1中,因此我只会在df2中选择第1行到第5行。

另外,我想根据df2重新排列df1。最终结果应该是这样的:

enter image description here

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

使用合并时,默认情况下,数据框由它们共有的变量连接,并对结果进行排序。所以你可以这样做:

merge(df2, df1[c('x', 'y')])

#   x y value
# 1 1 1    12
# 2 1 2    11
# 3 1 3     9
# 4 1 4    10
# 5 1 5     8

要按df1的顺序排序,请使用@ Mankind_008的方法

merge(df1[c('x','y')], df2 , sort = F)

示例:

set.seed(0)
df1 <- df1[sample(seq_len(nrow(df1))),]
df2 <- df2[sample(seq_len(nrow(df2))),]
df1
#   x y value
# 5 1 5     7
# 2 1 2     4
# 4 1 4     6
# 3 1 3     5
# 1 1 1     3    
merge(df1[c('x','y')], df2 , sort = F)
#   x y value
# 1 1 5     8
# 2 1 2    11
# 3 1 4    10
# 4 1 3     9
# 5 1 1    12

答案 1 :(得分:1)

使用数据表:

library(data.table)

将您的数据创建为data.table:

df1 <- data.table( x = c(1,1,1,1,1), y = c(1,2,3,4,5), value = c(3,4,5,6,7) )
df2 <- data.table( x = c(1,1,1,1,1,2), y = c(5,3,4,2,1,6), value = c(8,9,10,11,12,13) )

或转换现有的data.frames:

df1 <- as.data.table( df1 )
df2 <- as.data.table( df2 )

然后:

df2[ df1, on = .(x,y) ]

df1中df2中具有相同名称的任何列都将重命名为i.columnname:

   x y value i.value
1: 1 1    12       3
2: 1 2    11       4
3: 1 3     9       5
4: 1 4    10       6
5: 1 5     8       7

请注意,它已经按x和y排序。如果您想按列&#39;值排序&#39; (或任何其他):

df2[ df1, on = .(x,y) ][ order(value) ]

使用data.table(或dplyr,作为AntoniosK提出的解决方案)的优点是可以将两个数据集分开。

相关问题