[R] Create a new Vector based on two columns
Patrick Hausmann
patrick.hausmann at uni-bremen.de
Wed Apr 25 14:22:05 CEST 2012
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
More information about the R-help
mailing list