Bruh
Bruh

Reputation: 285

Assign multiple cell values based on conditions

Assume I have a dataset looking like this:

A     B     C
US
UK
UAE

I want to fill the values for B and C so that it looks like this:

If A = US or UK or UAE, then B = ONE and C = TWO,

A     B     C
US    ONE   TWO
UK    ONE   TWO
UAE   ONE   TWO

I would appreciate all the help. Thanks in advance!

Upvotes: 2

Views: 21

Answers (1)

TarJae
TarJae

Reputation: 78917

Here is a similar suggestion how you could do it:

library(tidyverse)

#data
df <- tribble(
  ~A,     ~B,     ~C,
"US", "", "",  
"UK", "", "",
"UAE", "", "")

# create a pattern to match
# this can be changed individually depending on what kind of values you want to match at the moment all values in column A are matched

pattern <- paste(df$A, collapse = "|")

df %>% 
  mutate(across(c(B,C), ~case_when(
    str_detect(A, pattern) & cur_column()=="B" ~ "ONE",
    str_detect(A, pattern) & cur_column()=="C"~ "TWO",
    TRUE ~ NA_character_)))
  A     B     C    
  <chr> <chr> <chr>
1 US    ONE   TWO  
2 UK    ONE   TWO  
3 UAE   ONE   TWO 

Upvotes: 1

Related Questions