具有相同数量变量的数据框列表并删除一个变量内的重复项,并对其余数据框执行相同操作

List of data frames with the same number of variables and delete duplicates inside one variable and do the same in the rest of the data frames

我有以下数据框列表,每个数据框都有 3 个变量(a、b 和 c)

my.list <- list(d1, d2, d3, d4)

在我的数据框中,我在“a”中有重复的字符串,我想删除具有重复值的行

我目前使用的代码:

my.listnew <- lapply(my.list, function(x) unique(x["a"]))

我对这段代码的问题是其他两列“b”和“c”消失了,我想保留它们,同时删除重复的行

使用 duplicated 删除列 a 中的重复值,同时保留其他列。

my.listnew <- lapply(my.list, function(x) x[!duplicated(x$a), ])

仅供参考,tidyverse 的做法-

set.seed(1)
my.list <- list(d1 = data.frame(a = sample(letters[1:3], 5, T),
                                b = rnorm(5),
                                c = rnorm(5)), 
                d2 = data.frame(a = sample(letters[1:3], 5, T),
                                b = rnorm(5),
                                c = rnorm(5)), 
                d3 = data.frame(a = sample(letters[1:3], 5, T),
                                b = rnorm(5),
                                c = rnorm(5)))
library(tidyverse)
map(my.list, ~ .x %>% filter(!duplicated(a)) )
#> $d1
#>   a         b          c
#> 1 a 1.5952808  0.5757814
#> 2 c 0.3295078 -0.3053884
#> 3 b 0.4874291  0.3898432
#> 
#> $d2
#>   a          b         c
#> 1 b  0.2522234 0.3773956
#> 2 a -0.8919211 0.1333364
#> 
#> $d3
#>   a          b          c
#> 1 a -0.2357066  1.1519118
#> 2 c -0.4333103 -0.4295131
#> 3 b -0.6494716  1.2383041

reprex package (v2.0.0)

于 2021-05-13 创建

如果您还想在输出中组合数据帧,您可以使用 map_dfr 而不是上面的 map

我们可以在没有任何匿名函数的情况下使用subset

out <- lapply(my.list, subset, subset = !duplicated(a))

或使用 data.tableunique

library(data.table)
out <- lapply(my.list, function(dat) unique(as.data.table(dat), by = 'a'))