merge two columns to one if value exist

Hi.
i'm trying to merge two columns but getting some issue.
my data looks like the following:

ad<-c("",3,4,5,6,7,"")
r<-c("2","3","","","6","","8")
dataw<-data.frame(ad,r)

> dataw
>   ad r
> 1    2
> 2  3 3
> 3  4  
> 4  5  
> 5  6 6
> 6  7  
> 7    8

this what I have done

mutate(dataw,New_Col=paste(ad,r))->dataw

the result looks like the following:

 ad  r   New_Col
     2   2
3    3   3 3
     4   4 
5        5 
6    6   6 6
7        7 
     8   8

I want the value to be added in the new column only if it exist in either ad or r. And if the value in ad an r are the same then only one should be added to the new column.
I need a solution that can be generalized to a large number of variables
How can I do this?
Thanks in advance

I think this does what you're after. Look into case_when() for more info:

library(tidyverse)

df <- tibble(
  ad = c("", 3, 4, 5, 6, 7, ""),
  r  = c("2", "3", "", "", "6", "", "8")
)

# using case_when()
df %>%
  mutate(newcol = case_when(
    ad == "" & r == "" ~ NA_character_,
    ad == "" & r != "" ~ r,
    ad != "" & r == "" ~ ad,
    ad == r ~ ad,
    TRUE ~ paste(ad, r)
  ))
#> # A tibble: 7 x 3
#>   ad    r     newcol
#>   <chr> <chr> <chr> 
#> 1 ""    "2"   2     
#> 2 "3"   "3"   3     
#> 3 "4"   ""    4     
#> 4 "5"   ""    5     
#> 5 "6"   "6"   6     
#> 6 "7"   ""    7     
#> 7 ""    "8"   8

Created on 2022-04-24 by the reprex package (v2.0.1)

perhaps :

mutate(dataw,
       new_col = pmax(r,ad))

Thanks. It worked fine on the sample, but not on my original data. I get these "NA". Is there a way to remove them?

#> # A tibble: 7 x 3
#>   ad    r     newcol
#>   <chr> <chr> <chr> 
#> 1 ""    "2"  NA 2     
#> 2 "3"   "3"   3     
#> 3 "4"   ""    4 NA     
#> 4 "5"   ""    5 NA
#> 5 "6"   "6"   6 
#> 6 "7"   ""    7 NA     
#> 7 ""    "8"   NA 8

it seems that your source data are characters, try to change them into numeric(using as.numeric())

or you can try this:

dataw %>% str_glue_data("{unique(c(ad,r))}")

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.