簡體   English   中英

如何在 R 的列序列中重新編碼值

[英]How to recode values in a columns sequence in R

如何在以下示例數據集中為i1:i3列重新編碼0110

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和來自dplyrmatches來改變以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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM