简体   繁体   中英

How to recode values in a columns sequence in R

How can I recode 0 to 1 and 1 to 0 for columns i1:i3 in the below sample dataset?

df <- data.frame(id = c(11,22,33),
                 i1 = c(0,1,NA),
                 i2 = c(1,1,0),
                 i3 = c(0,NA,1))

> df
  id i1 i2 i3
1 11  0  1  0
2 22  1  1 NA
3 33 NA  0  1

I have tens of columns starting with i.. . So I need a indexing condition to apply only for those columns. The desired output would be:

> df1
  id i1 i2 i3
1 11  1  0  1
2 22  0  0 NA
3 33 NA  1  0

You could approach this by indexing; would work fine if all variables beyond the id column begin with i as in the question.

df[, 2:4] <- ifelse(df[, 2:4] == 0, 1, 0)

# or more succinctly, following the examples of others, and still using `ifelse`

df[-1] <- ifelse(df[-1] == 0, 1, 0)
 
df
#>   id i1 i2 i3
#> 1 11  1  0  1
#> 2 22  0  0 NA
#> 3 33 NA  1  0

Created on 2022-10-10 with reprex v2.0.2

We can just negate and coerce

df[-1] <- +(!df[-1])

-output

> df
  id i1 i2 i3
1 11  1  0  1
2 22  0  0 NA
3 33 NA  1  0

We can simply use -

> df[-1] <- 1 - df[-1]

> df
  id i1 i2 i3
1 11  1  0  1
2 22  0  0 NA
3 33 NA  1  0

We can mutate only the columns beginning with i followed by a number using across and matches from dplyr and we can change values as you've specified using recode .

library(dplyr)
df %>%
  mutate(across(matches('^i\\d+'), recode, '1' = 0, '0' = 1))

Alternatively, in base R you can do this

i_cols <- str_detect(colnames(df), '^i\\d+')
df[,i_cols] <- ifelse(df[,i_cols] == 0, 1, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM