Reputation: 111
In trying to use unite to concatenate two numeric columns, I think this is turning the resulting column into a character string - how to avoid this?
df %>% unite(housinggrossconcat, housinggrossedupnet, housing.gross, na.rm=TRUE, remove=FALSE))
%>% unite(grossconcat, grossedupnet, gross, na.rm=TRUE, remove=FALSE)
Data looks like this:
Gross Grossedupnet New Column: Grossconcat
30 NA 30
NA 45 45
NA 45 45
350 NA 350
It is such that wherever Gross has a value, Grossedupnet will be NA, and vice versa. They're both numerical values. I want to concatenate the two into the new column, but it is turning the new column into a character variable.
Upvotes: 0
Views: 1355
Reputation: 887158
We can also use fcoalesce
library(data.table)
setDT(df)[, Grossconcat := fcoalesce(Gross, Grossedupnet)]
Upvotes: 0
Reputation: 145785
You're looking for coalesce
:
df %>%
mutate(Grossconcat = coalesce(Gross, Grossedupnet))
dplyr::coalesce()
is built for the purpose of taking the first non-missing value. It works on as many columns as you give it, and it works well for all data types. unite
is the complement to separate
. It is for pasting together strings, hence the character
output.
Upvotes: 1