[英]Remove duplicates from each row in R dataframe
I have a dataframe with 1209 columns, and 27900 rows. 我有一个具有1209列和27900行的数据框。
For each row there are duplicated values scatter around the columns. 对于每一行,重复的值分散在列周围。 I have tried transposing the dataframe and remove by columns.
我尝试过转置数据框并按列删除。 But it crashes.
但是它崩溃了。
After I transpose I used: 转置后,我使用了:
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
}
But no result so far. 但是到目前为止没有结果。
I would like to know if anyone has any idea. 我想知道是否有人有任何想法。
Best 最好
As I understand you would like to replace duplicated values in each column with NA? 据我了解,您想用NA替换每列中的重复值吗?
this can be done in several ways. 这可以通过几种方式来完成。
First some data: 首先一些数据:
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
with purrr library: 与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
with apply in base R 与适用于基数R
as.data.frame(apply(df, 2, function(x) ifelse(duplicated(x), NA, x)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.