我正在尝试从数据框中仅基于前一行删除重复行。函数duplicate
和unique
会删除所有重复项,只留下唯一的行,这不是我想要的。
我在此处使用循环演示了问题。我需要向量化这个过程,因为我的实际数据集太大,无法在循环中使用。
x <- c(1,1,1,1,3,3,3,4)
y <- c(1,1,1,1,3,3,3,4)
z <- c(1,2,1,1,3,2,2,4)
xy <- data.frame(x,y,z)
xy
x y z
1 1 1 1
2 1 1 2
3 1 1 1
4 1 1 1 #this should be removed
5 3 3 3
6 3 3 2
7 3 3 2 #this should be removed
8 4 4 4
# loop that produces desired output
toRemove <- NULL
for (i in 2:nrow(xy)){
test <- as.vector(xy[i,] == xy[i-1,])
if (!(FALSE %in% test)){
toRemove <- c(toRemove, i) #build a vector of rows to remove
}
}
xy[-toRemove,] #exclude rows
x y z
1 1 1 1
2 1 1 2
3 1 1 1
5 3 3 3
6 3 3 2
8 4 4 4
我尝试使用dplyr的
lag
函数,但它只适用于单个列,当我尝试在所有3列上运行它时,它不起作用。
ifelse(xy[,1:3] == lag(xy[,1:3],1), NA, xy[,1:3])
有任何建议如何完成这个任务吗?
mutate_each
,就可以使用dplyr::lag
来完成这个操作。例如,xy %>% mutate_each(funs(oneL = . - lag(.))) %>% mutate(dup = rowSums(select(. ,contains("oneL"))))%>% filter(dup != 0 | is.na(dup)) %>% select(x,y,z)
- Jacob H