I have a data frame dd2
with hundreds of columns and what I need to do is paste all these column values together omitting any NA
values. If I do something like this
apply(dd2, 1, paste, collapse=",")
it actually includes NA
s as "NA"
string. I want to avoid that. I could also do as shown below, but this would expect me to work for each individual column at a time to get the result.
result <- cbind(
dd2,
combination = paste(dd2[,2], replace(dd2[,3], is.na(dd2[,3]), ""), sep = ",")
)
Is there any efficient way to do it? Here is the sample data:
dd2 <- structure(c("A", "B", "C", "D", "E", "AK2", "HFM1", NA, "TRR",
"RTT", NA, "PPT", "TRR", "RTT", NA, "PPT", NA, NA, "GGT", NA), .Dim = c(5L,
4L), .Dimnames = list(NULL, c("sample_id", "plant", "animal",
"more")))
data.frame
. With "dd2", are you just trying to paste together all of the columns except the first? – Daynadd2[,wanted.columns]
. – Kaleenamelt(as.data.table(dd2), measure.vars = c("plant", "animal"), na.rm = TRUE)[, toString(value), by = .(sample_id, more)]
. – Dayna