Insert custom columns

I want to insert several columns with some text where they are combined, only if at least one is not NA, and the current solution works for me, but it is cumbersome. So I'm wondering if there is an easier way to do this (create a β€œcombine” column below). I would like to use tidyr, but there seems to be no way to specify how to handle missing values ​​in unite ()

Thank you and I hope that I have not missed anything 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>
+4
source share
2 answers

, (: ), , . -NA :

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

, :

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

mutate ifelse dplyr

library(dplyr)
df %>%
   mutate(combine = ifelse(rowSums(!is.na(.))>0, paste(num, "days in", place), NA))
#    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>

data.table

library(data.table)
setDT(df)[df[, !Reduce(`&`, lapply(.SD, is.na))], combine := paste(num, "days in", 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
+1

Source: https://habr.com/ru/post/1652444/


All Articles