我有一个结构如下所示的数据集。
# example data set
a <- "a"
b <- "b"
d <- "d"
id1 <- c(a,a,a,a,b,b,d,d,a,a,d)
id2 <- c(b,d,d,d,a,a,a,a,b,b,d)
id3 <- c(b,d,d,a,a,a,a,d,b,d,d)
dat <- rbind(id1,id2,id3)
dat <- data.frame(dat)
我需要在每一行中找到具有重复元素“a”的第一个序列,并立即识别序列后面的元素。
# desired results
dat$s3 <- c("b","b","d")
dat
我能够分 3 个步骤解决问题并解决第一个问题,但由于我的编程技能非常有限,如果您能就如何处理第 2 步和第 3 步提出任何建议,我将不胜感激。如果您有解决问题的想法以另一种方式也将非常有帮助。
这是我目前所拥有的:
# Step 1: find the first occurence of "a" in the fist sequence
dat$s1 <- apply(dat, 1, function(x) match(a,x))
# Step 2: find the last occurence in the first sequence
# Step 3: find the element following the last occurence in the first sequence
提前致谢!
最佳答案
我会使用过滤器
:
fun <- function(x) {
x <- as.character(x)
isa <- (x == "a") #find "a" values
#find sequences with two TRUE values and the last value FALSE
ids <- stats::filter(isa, c(1,1,1), sides = 1) == 2L & !isa
na.omit(x[ids])[1] #subset
}
apply(dat, 1, fun)
#id1 id2 id3
#"b" "b" "d"
关于r - 在数据框中的跨行序列中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40526079/