Search code examples
rif-statementmultiple-columnsselection

if condition is true, set all other column values to 0 - R


I create a random dataset via:

#create dataset
first_column <- c(1:10) #random column
second_column <- c(1:10) #random column
third_column <- c(1:10) #random column
group <- c(1,1,1,2,2,1,2,1,1,1) #column used for selection

#merge columns
df <- data.frame(first_column, second_column, third_column, group)

#examine
print(df)

which outputs:

   first_column second_column third_column group
1             1             1            1     1
2             2             2            2     1
3             3             3            3     1
4             4             4            4     2
5             5             5            5     2
6             6             6            6     1
7             7             7            7     2
8             8             8            8     1
9             9             9            9     1
10           10            10           10     1

I would like to set the values of columns first_column, second_column, and third_column to 0 if the value of group is equal to 2 (while retaining the values if the value of group equals 1), which should result in:

   first_column second_column third_column group
1             1             1            1     1
2             2             2            2     1
3             3             3            3     1
4             0             0            0     2
5             0             0            0     2
6             6             6            6     1
7             0             0            0     2
8             8             8            8     1
9             9             9            9     1
10           10            10           10     1

What is the most convenient way to reach this?


Solution

  • We could create the logical index with group as i and assign the columns 1 to 3 as 0

    df[df$group == 2, 1:3] <- 0
    

    -output

    > df
       first_column second_column third_column group
    1             1             1            1     1
    2             2             2            2     1
    3             3             3            3     1
    4             0             0            0     2
    5             0             0            0     2
    6             6             6            6     1
    7             0             0            0     2
    8             8             8            8     1
    9             9             9            9     1
    10           10            10           10     1