我有一个维度为 58000*900 的 df,它包含行值中的重复项,我想遍历每一行并删除它们。举个例子会更清楚。
df
IDs Name col1 col2 col3
123 AB.C 1.3,1.3,1.3,1.3,1.3 0,0,0,0,0 5,5,5,5,5
234 CD-E 2,2,2,2,2 0.3,0.3,0.3,0.3,0.3 1,1,1,1,1
568 GHJ 123456 123456 123456
345 FGH 9,9,9,9,9 54,54,54,54,54 0,0,0,0,0
显然每个值都被复制了 5 次,在某些情况下,它们的问题是没有 .
或 ,
分隔值。
我想要的是删除那些不包含 .
或 ,
的行,其余的删除重复值。因此,输出将是:
IDs Name col1 col2 col3
123 AB.C 1.3 0 5
234 CD-E 2 0.3 1
345 FGH 9 54 0
dput(df)
structure(list(IDs = c(123L, 234L, 568L, 345L), Name = structure(c(1L,
2L, 4L, 3L), .Label = c("ABC", "CDE", "FGH", "GHJ"), class = "factor"),
col1 = structure(c(2L, 3L, 1L, 4L), .Label = c("123456",
"1.3,1.3,1.3,1.3,1.3", "2,2,2,2,2", "9,9,9,9,9"), class = "factor"),
col2 = structure(1:4, .Label = c("0,0,0,0,0", "0.3,0.3,0.3,0.3,0.3",
"123456", "54,54,54,54,54"), class = "factor"), col3 = structure(c(4L,
2L, 3L, 1L), .Label = c("0,0,0,0,0", "1,1,1,1,1", "123456",
"5,5,5,5,5"), class = "factor")), .Names = c("IDs", "Name",
"col1", "col2", "col3"), class = "data.frame", row.names = c(NA,
-4L))
最佳答案
首先,我们使用 gather()
以长格式重组您的数据,然后我们使用 filter()
获取 value
而不使用 ,
使用 grepl()
。然后,我们使用 strsplit()
将 value
中的字符串拆分为一个列表,并使用 unnest()
使列表中的每个元素成为自己的行。我们使用 distinct()
和 spread()
删除重复的行,将 key
和 values
返回到列。
library(dplyr)
library(tidyr)
df %>%
gather(key, value, -(IDs:Name)) %>%
filter(grepl(",", value)) %>%
mutate(value = strsplit(value, ",")) %>%
unnest(value) %>%
distinct %>%
spread(key, value)
给出:
#Source: local data frame [3 x 5]
#
# IDs Name col1 col2 col3
# (int) (fctr) (chr) (chr) (chr)
#1 123 AB.C 1.3 0 5
#2 234 CD-E 2 0.3 1
#3 345 FGH 9 54 0
另一个想法是使用 splitstackshape
中的 cSplit
:
df %>%
cSplit(., c("col1", "col2", "col3"), direction = "long", sep = ",") %>%
group_by(Name) %>%
filter(!any(is.na(.))) %>%
distinct
给出:
#Source: local data table [3 x 5]
#Groups: Name
#
# IDs Name col1 col2 col3
# (int) (fctr) (dbl) (dbl) (int)
#1 123 AB.C 1.3 0.0 5
#2 234 CD-E 2.0 0.3 1
#3 345 FGH 9.0 54.0 0
关于从行中的值中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37461985/