R paste0 2 columns if not NA -
i paste0
2 columns if element in 1 column not na
.if 1 element
of 1 columns na
keep element of other column only.
structure(list(col1 = structure(1:3, .label = c("a", "b", "c"), class = "factor"), col2 = c(1, na, 3)), .names = c("col1", "col2"), class = "data.frame",row.names = c(na, -3l)) # col1 col2 # 1 1 # 2 b na # 3 c 3 structure(list(col1 = structure(1:3, .label = c("a", "b", "c"), class = "factor"),col2 = c(1, na, 3), col3 = c("a|1", "b", "c|3")), .names = c("col1", "col2", "col3"), row.names = c(na,-3l), class = "data.frame") # col1 col2 col3 #1 1 a|1 #2 b na b #3 c 3 c|3
as @roland says, easy using ifelse
(just translate mental logic series of nested ifelse
statements):
x <- transform(x,col3=ifelse(is.na(col1),as.character(col2), ifelse(is.na(col2),as.character(col1), paste0(col1,"|",col2))))
update: need as.character
in cases.
Comments
Post a Comment