Search code examples
rrowsum

Assigning values to a column in the based on values of another column in the same dataframe in R


I have a dataframe with 3 columns and I want to assign values to a fourth column of this dataframe if the sum of a condition is met in another row. In this example I want to assign 1 to df[,4], if df[,3]>=2 for each row.

An example of what I want as the output is:

enter image description here

Any help is appreciated.

Thank you,


Solution

  • library(tidyverse)
    
    data <- 
        tribble(
            ~ID, ~time1, ~time2,
            'jkjkdf', 1, 1,
            'kjkj', 1, 0,
            'fgf', 1, 1,
            'jhkj', 0, 1, 
            'hgd', 0,0
        )
    
    mutate(data, label = if_else(time1 + time2 >= 2, 1, 0))
    #> # A tibble: 5 x 4
    #>   ID     time1 time2 label
    #>   <chr>  <dbl> <dbl> <dbl>
    #> 1 jkjkdf     1     1     1
    #> 2 kjkj       1     0     0
    #> 3 fgf        1     1     1
    #> 4 jhkj       0     1     0
    #> 5 hgd        0     0     0
    
    #or with n time columns
    
    data %>%
        rowwise() %>% 
        mutate(label = if_else(sum(across(starts_with('time'))) >= 2, 1, 0))
    #> # A tibble: 5 x 4
    #> # Rowwise: 
    #>   ID     time1 time2 label
    #>   <chr>  <dbl> <dbl> <dbl>
    #> 1 jkjkdf     1     1     1
    #> 2 kjkj       1     0     0
    #> 3 fgf        1     1     1
    #> 4 jhkj       0     1     0
    #> 5 hgd        0     0     0
    

    Created on 2021-06-06 by the reprex package (v2.0.0)