Home > Software engineering >  Ifelse applied to an interval of columns, but keeping all the other columns
Ifelse applied to an interval of columns, but keeping all the other columns

Time:11-30

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.

CodePudding user response:

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

CodePudding user response:

As I misunderstood your question, this is probably not the best solution. So I proposed the index counter variable

  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$index <- 1:nrow(df)

df2 <- as.data.frame(ifelse(df[2:3] == 1, 2, 0))
df2$index = cbind(df$index)
df2$x=cbind(df[1])

df2 <- df2[, c("index", "x", "y", "z")]
df2

 index   x y z
1     1 123 2 0
2     2 121 0 0
3     3 120 0 0
4     4 124 0 0
5     5 125 2 2
  • Related