Impossible9 Impossible9 - 3 months ago 19
R Question

Pasting together subsetted columns

I want to paste together some columns with some text where they are combined only if at least one is not NA and the current solution I have works, but is cumbersome. So I am wondering if there is a neater way to do this (to create the "combine" column below). I would like to have used tidyr but there doesn't seem to be a way to specify how to treat missing values in unite()

Thanks and I hope I haven't missed something obvious.

df = data.frame(num=c(1,2,NA,NA),place=c("Rome",NA,"Paris",NA))

df$combine[!is.na(df$num)|!is.na(df$place)] =
paste(df$num[!is.na(df$num)|!is.na(df$place)],
"days in",df$place[!is.na(df$num)|!is.na(df$place)])

# df
# num place combine
# 1 1 Rome 1 days in Rome
# 2 2 <NA> 2 days in NA
# 3 NA Paris NA days in Paris
# 4 NA <NA> <NA>

Answer

Whenever you find yourself computing the same thing (here: index) again, try to store it and reuse that object to avoid redundant computation. For your example, you could compute the non-NA index as follows:

idx <- rowSums(!is.na(df)) > 0

Then, you can use that to paste the relevant rows together:

df[idx, "combine"] <- with(df[idx, ], paste(num, "days in", place))