Hello,

I am trying to get a new vector 'x1' based on the not NA-values in column 'a' and 'b'. I found a way but I am sure this is not the best solution. So any ideas on how to "optimize" this would be great!

m <- factor(c("a1", "a1", "a2", "b1", "b2", "b3", "d1", "d1"), ordered = TRUE)
df <- data.frame( a= m, b = m)
df[1,1] <- NA
df[4,2] <- NA
df[2,2] <- NA
df[6,1] <- NA
df

w <- !apply(df, 2, is.na)
v <- apply(w, 1, FUN=function(L) which(L == TRUE)[[1]])

for (i in 1:nrow(df) ) {
    g[i] <- df[i, v[i]]
}

df$x1 <- g

Thanks for any help
Patrick

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to