r - Find an element following a sequence across rows in a data frame -


i have data set structure shown below.

# example data set   <- "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) 

i need find across each row first sequence repeated elements "a" , identify element following sequence immediately.

# desired results  dat$s3 <- c("b","b","d") dat  

i able break problem in 3 steps , solve first 1 programming skills quite limited, appreciate advice on how approach steps 2 , 3. if have idea solves problem in way extremely helpful well.

here have far:

# step 1: find first occurence of "a" in fist sequence  dat$s1 <- apply(dat, 1, function(x) match(a,x))  # step 2: find last occurence in first sequence   # step 3: find element following last occurence in first sequence 

thanks in advance!

i'd use filter:

fun <- function(x) {   x <- as.character(x)   isa <- (x == "a") #find "a" values    #find sequences 2 true values , 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"  

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -