Search code examples
rif-statementmultiple-columns

Ifelse applied to an interval of columns, but keeping all the other columns


I would like to use the ifelse function to attribute new values to a set of columns in a df. The real df has >200 columns, so I can't state the names of the columns, instead, I need to specify the interval of columns (e.g. 2:205).

df <- data.frame(x=c(123, 121, 120, 124, 125), y=c(1, 0, 0, 0, 1), z=c(0,0, 0, 0, 1))
df
    x y z
1 123 1 0
2 121 0 0
3 120 0 0
4 124 0 0
5 125 1 1

However, when I do specify the interval of columns, the first column is skipped. How can I keep the first column unchanged?

df2 <- as.data.frame(ifelse(df[2:3] == 1, 2, 0))
df2
  y z
1 2 0
2 0 0
3 0 0
4 0 0
5 2 2

Thanks.


Solution

  • The simples solution would be to use your current code, but reassign your output to the same subset of the original data with df[2:3]<-function(df[2:3]):

    df2<-df
    df2[2:3]<- as.data.frame(ifelse(df[2:3] == 1, 2, 0))
    df2
        x y z
    1 123 2 0
    2 121 0 0
    3 120 0 0
    4 124 0 0
    5 125 2 2
    

    Or we can use dplyr:

    library(dplyr)
    
    df %>% mutate(across(2:3, ~ifelse(.x==1, 2, 0)))
    
        x y z
    1 123 2 0
    2 121 0 0
    3 120 0 0
    4 124 0 0
    5 125 2 2