Coalesce Two String Columns With Alternating Missing Values to One

Coalesce two string columns with alternating missing values to one

You may try pmax

df$c <- pmax(df$a, df$b)
df
# a b c
# 1 dog <NA> dog
# 2 mouse <NA> mouse
# 3 <NA> cat cat
# 4 bird <NA> bird

...or ifelse:

df$c <- ifelse(is.na(df$a), df$b, df$a)

For more general solutions in cases with more than two columns, you find several ways to implement coalesce in R here.

Is there an R function that unifies multiple columns?

We can use coalesce

library(dplyr)
df <- df %>%
mutate(C = coalesce(A, B))

Is there a way to combine information from two columns into a single column in R?

We can use coalecse from dplyr

library(dplyr)
df1 %>%
transmute(coln = coalecse(col1, col2))

Collapse rows with complementary column data in a data.table in r

Maybe this will help :

library(dplyr)

df.in %>%
group_by(tkr) %>%
summarise(across(lboq:ap, ~.x[.x != 0][1]))

# tkr lboq locq ap
#* <chr> <dbl> <dbl> <dbl>
#1 abc 296 -296 134
#2 def -390 390 23
#3 ghi -88 88 17

For each tkr this selects the 1st non-zero value in columns lboq:ap.

Merge values from two columns to overwrite NAs in same row in R

Using dplyr:

library(dplyr)
MergingTABLE %>%
mutate(c = if_else(is.na(b), a, b))

What is the best way to merge two numeric variables with missing values?

Using base R you could do:

dt$age <- ifelse(is.na(dt$age1), dt$age2, dt$age1)

Or, using dplyr:

coalesce(age1, age2)

This gives us the vector:

[1] 20 21 22 23 24 25 26 NA

If you want to create an age variable in your dt dataframe:

dt %>% 
mutate(age = coalesce(age1, age2))

Which gives us:

  age1 age2 age
1 NA 20 20
2 21 NA 21
3 22 NA 22
4 NA 23 23
5 24 NA 24
6 25 NA 25
7 NA 26 26
8 NA NA NA


Related Topics



Leave a reply



Submit