Impossible9 Impossible9 - 10 months ago 59
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[!$num)|!$place)] =
"days in",df$place[!$num)|!$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>


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(! > 0

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

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