在多个数据框中为一列查找公共值的最有效方法
Most efficient way to find common values for one column across many data frames
我有很多文件,我正在尝试找到读取数据框并在一列中查找共同值的最有效方法。
现在我有:
1. 我使用以下方法读取文件列表:
files = c("test1.txt", "test2.txt", test3.txt")
my.data <- lapply(files, read.table, header=T)
每个包含列,例如
df1 = data.frame(id=c("a", "b", "c"), v = c(1:3), c=c(10:12))
df2 = data.frame(id=c("x", "b", "c"), v = c(2:4), c=c(13:15))
df3 = data.frame(id=c("a", "n", "c"), v = c(4:6), c=c(16:18))
my.data = list(df1, df2, df3)
现在我正在尝试将数据帧列表子集化为 return 相同的数据帧列表,每个数据帧仅包含名为 "id" 的第一列的公共行,例如
df1, df2, and df3 in this case would be a list containing only "id" common to all read files, i.e. a row with only "c" in this case:
intersect(intersect(df1$id, df2$id), df3$id);
list(df1[3,], df2[3,], df3[3,])
但我想不出一种使用列表来合并所有数据框的方法,也许这是一个 longer/more 比读取所有文件,首先通过公共列合并它们更困难的过程 "id",然后将它们拆分成一个数据框列表?有没有人对最有效的方法有任何见解?谢谢!
要找到 id
列的公共交集,您可以使用
common <- Reduce(intersect, Map("[[", my.data, "id"))
然后我们可以使用它来对列表元素进行子集化。
lapply(my.data, function(x) x[x$id %in% common, ])
# [[1]]
# id v c
# 3 c 3 12
#
# [[2]]
# id v c
# 3 c 4 15
#
# [[3]]
# id v c
# 3 c 6 18
我有很多文件,我正在尝试找到读取数据框并在一列中查找共同值的最有效方法。
现在我有: 1. 我使用以下方法读取文件列表:
files = c("test1.txt", "test2.txt", test3.txt")
my.data <- lapply(files, read.table, header=T)
每个包含列,例如
df1 = data.frame(id=c("a", "b", "c"), v = c(1:3), c=c(10:12))
df2 = data.frame(id=c("x", "b", "c"), v = c(2:4), c=c(13:15))
df3 = data.frame(id=c("a", "n", "c"), v = c(4:6), c=c(16:18))
my.data = list(df1, df2, df3)
现在我正在尝试将数据帧列表子集化为 return 相同的数据帧列表,每个数据帧仅包含名为 "id" 的第一列的公共行,例如
df1, df2, and df3 in this case would be a list containing only "id" common to all read files, i.e. a row with only "c" in this case:
intersect(intersect(df1$id, df2$id), df3$id);
list(df1[3,], df2[3,], df3[3,])
但我想不出一种使用列表来合并所有数据框的方法,也许这是一个 longer/more 比读取所有文件,首先通过公共列合并它们更困难的过程 "id",然后将它们拆分成一个数据框列表?有没有人对最有效的方法有任何见解?谢谢!
要找到 id
列的公共交集,您可以使用
common <- Reduce(intersect, Map("[[", my.data, "id"))
然后我们可以使用它来对列表元素进行子集化。
lapply(my.data, function(x) x[x$id %in% common, ])
# [[1]]
# id v c
# 3 c 3 12
#
# [[2]]
# id v c
# 3 c 4 15
#
# [[3]]
# id v c
# 3 c 6 18