Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column to data frame resulting from the merging of some values from other columns with R

Tags:

dataframe

r

I have a data frame with many columns, among which I have the following:

COLUMN_1   COLUMN_2   COLUMN_3
red        blue       green
none       blue       none
red        none       green
red        none       none
none       none       none

I'd like to add a fourth column called COLORS based on a boolean which gives 'True' for every value 'red' of COLUMN_1, 'blue' of COLUMN_2, or 'green' of COLUMN_3, and gives 'False' if the value of COLUMN_1, COLUMN_2 and COLUMN_3 is always 'none'. Like this:

   COLUMN_1   COLUMN_2   COLUMN_3    COLORS
    red        blue       green      True
    none       blue       none       True
    red        none       green      True
    red        none       none       True
    none       none       none       False

A column without a boolean would also work:

COLUMN_1   COLUMN_2   COLUMN_3   COLORS
red        blue       green      Color
none       blue       none       Color
red        none       green      Color
red        none       none       Color
none       none       none       No color
like image 507
afr100 Avatar asked Dec 21 '25 09:12

afr100


1 Answers

library(dplyr) 

df %>%  
  mutate(
    COLORS = case_when(
      if_all(contains("COLUMN"), ~ .x == "none") ~ "No color", 
      TRUE ~ "Color"
    ))

# A tibble: 5 × 4
  COLUMN_1 COLUMN_2 COLUMN_3 COLORS  
  <chr>    <chr>    <chr>    <chr>   
1 red      blue     green    Color   
2 none     blue     none     Color   
3 red      none     green    Color   
4 red      none     none     Color   
5 none     none     none     No color
like image 164
HoelR Avatar answered Dec 23 '25 21:12

HoelR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!