Home > Back-end >  R Replace value or keep value in one column with value from another column in the same row with cert
R Replace value or keep value in one column with value from another column in the same row with cert

Time:08-18

I have an additional question after Replace value in one column with value from another column in the same row with certain condition

I have a data frame with columns "A", "B", and "Dict"

Now, the difference between the former question and this one is "Dict" has values of "A","B", and "C"

"A" and "B" indicates the correct columns that values should be in for each row, and I want to leave "C" unchanged

For example:

A            B             Dict
0           123            B
0           123            A
123         0              A
123         0              C
0           123            C

I want to move the value in "B" to "A" if "Dict" has A in the same row, and replace the value with 0. If "Dict" has C, then the row is unchanged:

A            B             Dict
0           123             B
123          0              A
123          0              A
123          0              C
0           123             C

Currently I am using Daren Tsai's answer in the previous question:

df %>%
  mutate(across(A:B, ~ ifelse(Dict == cur_column(), A B, 0))) 

but it gives me

A            B             Dict
0           123             B
123          0              A
123          0              A
0            0              C
0            0              C

Does anyone know how I can change the function so when "Dict" has value C it does not change the row to zero?

CodePudding user response:

How about just adding another condition to your conditional statement?

read_table("A            B             Dict
0           123            B
0           123            A
123         0              A
123         0              C
0           123            C
") %>%
  mutate(across(A:B, ~case_when(Dict == cur_column() ~ A B,
                                Dict == "C" ~ .,
                                TRUE ~ 0))) 

# # A tibble: 5 × 3
#       A     B Dict 
#   <dbl> <dbl> <chr>
# 1     0   123 B    
# 2   123     0 A    
# 3   123     0 A    
# 4   123     0 C    
# 5     0   123 C    
  • Related