[英]How to recode values in a columns sequence in R
如何在以下示例數據集中為i1:i3
列重新編碼0
到1
和1
到0
?
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..
開頭的專欄。 所以我需要一個索引條件來僅適用於那些列。 所需的 output 將是:
> df1
id i1 i2 i3
1 11 1 0 1
2 22 0 0 NA
3 33 NA 1 0
您可以通過索引來解決這個問題; 如果id
列之外的所有變量都以問題中的 i 開頭,則可以正常工作。
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
創建於 2022-10-10,使用reprex v2.0.2
我們只能否定和強制
df[-1] <- +(!df[-1])
-輸出
> df
id i1 i2 i3
1 11 1 0 1
2 22 0 0 NA
3 33 NA 1 0
我們可以簡單地使用-
> 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
我們只能使用across
和來自dplyr
的matches
來改變以i
開頭后跟數字的列,我們可以使用recode
更改您指定的值。
library(dplyr)
df %>%
mutate(across(matches('^i\\d+'), recode, '1' = 0, '0' = 1))
或者,在基地 R 你可以這樣做
i_cols <- str_detect(colnames(df), '^i\\d+')
df[,i_cols] <- ifelse(df[,i_cols] == 0, 1, 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.