[英]How to remove duplicated rows based on 3 columns for only one factor level?
我有一个包含130
数据框的列表,每个数据框有27
列,每个数据框有2
因子级别。 我想删除每个数据框中的重复行,仅基于一个因子级别的3
列,保留另一个因子级别中的所有行及其重复项。
我已经根据因子级别对所有数据框进行了排序,然后我尝试仅删除第一个因子级别的重复行。
该列表在列表中的数据帧之间称为x
和i
索引,其中包含x[[i]]
,其中i
从1
到130
运行。
每个名为temp
数据框中的列包含2
因子水平, 0
或1
。 130
数据帧已根据level = 0
首先排序,然后level=1
。
for (i in 1:130)
{
x[[i]]$temp <- factor(x[[i]]$temp,levels = c(0,1))
# Creating 2 factor levels called `0` and `1` in column called `temp` and index position of the `temp` column is `24`
x[[i]] <- x[[i]][order(x[[i]]$temp),]
# Ordering all of the dataframes by levels; level = 0 first then level = 1
x[[i]] <- x[[i]][!(duplicated(x[[i]][c(2,27,25)])),]
# This is removing duplicated based on columns 2,27 and 25, but I to perform this only for the first factor level = 0
}
对于单个数据框,比如说df
,您可以执行以下操作:
library(dplyr)
df %>% distinct(temp, 2, 27, 25, .keep_all = TRUE)
请注意,您不必考虑对因子进行分组,因为如果两个因子的行都具有重复值的列 2、27 和 25,它们仍然是两个不同的列。
这里的关键是参数.keep_all
,它保留剩余的列。 但是请注意,如果剩余的列在某些原因上有所不同,则不确定您返回哪些行,对于temp
和第 2、27 和 25 列的每个不同组合,您只会获得 1 行。
要扩展到 data.frames 列表,您可以使用lapply
:
lapply(x, function(df) {
df %>% distinct(temp, 2, 27, 25, .keep_all = TRUE)
}) %>% bind_rows(.id='date')
其中对bind_rows
的最后一次调用只是将所有内容压缩到单个数据框中,并添加.id
参数以添加名为date
的列,其值应为输入列表中的条目名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.