r - Preserve NA in output of ifelse statement using paste -



r - Preserve NA in output of ifelse statement using paste -

i have info organized below m1 - m4, , utilize code here generate m_new:

m1 m2 m3 m4 m_new 1 1,2 0 1 1 3,4 3,4 1,2,3,4 4 3,4 na na 1 2 na

it looks specified number of occurneces of number in 4 columns , reports numbers in m_new. now, include numbers 0 , 21 each of observations, unless observation na. however, far, unable paste 0 , 21 observations, without pasting them na values. desired output include in df below m_new1. how can accomplished? appears missing paste here.

# sample info df <- structure(list(m1 = structure(c(3l, 4l, 2l, 2l, 1l, 5l, na, 6l ), .label = c("0", "1", "1,2", "1,2,3,4", "1,2,3,4,5", "3,4,5,6,7" ), class = "factor"), m2 = structure(c(3l, na, 2l, 2l, 1l, 4l, na, 5l), .label = c("0", "1,2", "1,2,3,4,5", "4,5,6", "4,5,6,7,8,9,10,11,12,13,14" ), class = "factor"), m3 = structure(c(3l, na, 1l, 1l, 1l, 2l, na, 4l), .label = c("0", "1,2,3,4", "1,2,3,4,5", "1,2,3,4,5,6,7,8" ), class = "factor"), m4 = structure(c(3l, na, 1l, 2l, 1l, 5l, na, 4l), .label = c("0", "1", "1,2,3,4,5,6", "1,2,3,4,5,6,7,8,9,10,11,12", "4,5"), class = "factor"), m_new1 = structure(c(3l, na, 1l, 2l, 1l, 5l, na, 4l), .label = c("0,21", "1,0,21", "1,2,3,4,5,0,21", "3,4,5,6,7,8,0,21", "4,5,0,21"), class = "factor")), .names = c("m1", "m2", "m3", "m4", "m_new1"), class = "data.frame", row.names = c(na, -8l)) # function modified http://stackoverflow.com/a/23203159/1670053 f <- function(x, n=3) { tab <- table(strsplit(paste(x, collapse=","), ",")) res <- paste(names(tab[which(tab >= n)]), collapse=",") return(ifelse(is.na(res), na, ifelse(res == 0, "0,21", paste(res,",0,21",sep="")))) #return(ifelse(is.na(res), ifelse(res == 0, "0,21", na), paste(res,",0,21",sep=""))) #http://stackoverflow.com/a/17554670/1670053 #return(ifelse(is.na(res), na, ifelse(res == 0, "0,21", paste(na.omit(res),",0,21",sep="")))) #return(ifelse(is.na(res), as.character(na), ifelse(res == 0, "0,21", paste(res,",0,21",sep="")))) } df$m_new2 <- apply(df[, 1:4], 1, f))

you can add together if else statement - rather inelegant gets there.

f2 <- function(x, n=3) { tab <- table(strsplit(paste(x, collapse=","), ",")) res <- paste(names(tab[which(tab >= n)]), collapse=",") res <- ifelse(res %in% c("0", ""), "0,21", res) if(res %in% c("na","0,21")) res else paste(res, "0,21", sep=",") } apply(df[1:4], 1, f2) # "1,2,3,4,5,0,21" "na" "0,21" "1,0,21" "0,21" "4,5,0,21" "na" # "3,4,5,6,7,8,0,21"

r if-statement data.frame na

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -