这是我的函数:
my_func <- function(x){
ifelse(duplicated(x), NA_real_, first(x))
}
我想将其应用于此向量:
vector <- c(1,1,1,3,3,3)
[1] 1 1 1 3 3 3
我的预期输出:
[1] 1 NA NA 3 NA NA
我尝试过sapply
:
sapply(vector, my_func)
gives:
[1] 1 1 1 3 3 3
or changed the function to
my_func <- function(x){
ifelse(duplicated(x), NA_real_, x)
}
replace_dup = function(x, val = NA_real_) {
x[duplicated(x)] = val
x
}
replace_dup(vector)
[1] 1 NA NA 3 NA NA
对于要替换的索引,duplicated(x)
将是TRUE
,因此可以用这些索引对向量进行子集化并替换它们。
我不知道为什么ifelse(duplicated(x), NA_real_, x)
不适用于您,因为这也是一个有效的解决方案(尽管稍微复杂一些(。当我运行它并产生正确的结果时,它工作得很好。
至于sapply()
——如果你有一个列表,你想应用这个函数,那就行了:
vectors = list(c(1, 1, 2, 1, 3), c(5, 5, 5))
sapply(vectors, replace_dup)
[[1]]
[1] 1 NA 2 NA 3
[[2]]
[1] 5 NA NA
编辑:正如评论中所提到的,这里sapply()
的问题是,该函数已经设计为与整个向量一起工作。sapply(vector, replace_dup)
将replace_dup()
应用于vector
的每个单独元素,从而不会识别出重复:
sapply(vector, replace_dup)
[1] 1 1 1 3 3 3