[R] Create new Vector based on two colums
ilai
keren at math.montana.edu
Wed Apr 25 17:29:44 CEST 2012
On Wed, Apr 25, 2012 at 6:14 AM, Patrick Hausmann
<patrick.hausmann at covimo.de> wrote:
> 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!
If by optimize you mean no loops, you could try
(df<- structure(list(a = structure(c(NA, 1L, 2L, 3L, 4L, NA, 6L, 6L
), .Label = c("a1", "a2", "b1", "b2", "b3", "d1"), class = c("ordered",
"factor")), b = structure(c(1L, NA, 2L, NA, 4L, 5L, 6L, 6L), .Label = c("a1",
"a2", "b1", "b2", "b3", "d1"), class = c("ordered", "factor"))),
.Names = c("a",
"b"), row.names = c(NA, -8L), class = "data.frame"))
x0 <- factor(paste(ifelse(is.na(df[,1]),'',df[,1]),
ifelse(is.na(df[,2]),'',df[,2]), sep=''))
df$x1 <- as.numeric(x0) # only needed for a numeric vector as in your solution
df
HTH
PS - In the future please avoid "df" and "data" as object names, as
they mask R functions.
> 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 at 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.
More information about the R-help
mailing list