繁体   English   中英

从R数据框中的每一行中删除重复项

[英]Remove duplicates from each row in R dataframe

我有一个具有1209列和27900行的数据框。

对于每一行,重复的值分散在列周围。 我尝试过转置数据框并按列删除。 但是它崩溃了。

转置后,我使用了:

for(i in 1:ncol(df)){

        #replicate column i without duplicates, fill blanks with NAs
        df <-  cbind.fill(df,unique(df[,1]), fill = NA)
        #rename the new column
        colnames(df)[n+1] <- colnames(df)[1]
        #delete the old column
        df[,1] <- NULL
}

但是到目前为止没有结果。

我想知道是否有人有任何想法。

最好

据我了解,您想用NA替换每列中的重复值吗?

这可以通过几种方式来完成。

首先一些数据:

set.seed(7)
df <- data.frame(x = sample(1: 20, 50, replace = T),
                 y = sample(1: 20, 50, replace = T),
                 z = sample(1: 20, 50, replace = T))
head(df, 10)
#output
    x  y  z
1  20 12  8
2   8 15 10
3   3 16 10
4   2 13  8
5   5 15 13
6  16  8  7
7   7  4 20
8  20  4  1
9   4  8 16
10 10  6  5

与purrr库:

library(purrr)
map_dfc(df, function(x) ifelse(duplicated(x), NA, x))
#output
# A tibble: 50 x 3
       x     y     z
   <int> <int> <int>
 1    20    12     8
 2     8    15    10
 3     3    16    NA
 4     2    13    NA
 5     5    NA    13
 6    16     8     7
 7     7     4    20
 8    NA    NA     1
 9     4    NA    16
10    10     6     5
# ... with 40 more rows

与适用于基数R

as.data.frame(apply(df, 2, function(x) ifelse(duplicated(x), NA, x)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM