r-将响应更改为1,将NA更改为2

  • 本文关键字:NA 响应 r rename
  • 更新时间 :
  • 英文 :


如何将任何响应/值重命名为1,将任何NA重命名为0?

示例数据帧:

Dataframeexample <- data.frame(Q5 = c("potato", "chips", "chips", "chips,potato","icecream,chips,potato", "icecream,potato", "chips", "NA", "NA"))

我的实际数据帧有数百个潜在的组合,因此单独重命名每个潜在值是不可行的。

首先,如果您确实有这些数据,请将"NA"字符串转换为真正的NA

dat[dat == "NA"] <- NA

然后立即重命名整个数据帧中的值:

dat[!is.na(dat)] <- 1
dat[is.na(dat)] <- 0
dat
#   Q5 Q6
# 1  1  1
# 2  1  1
# 3  1  1
# 4  0  0
# 5  0  0

不需要包或循环。


数据:

dat <- data.frame(Q5 = c("potato", "chips", "chips,potato", "NA", "NA"),
Q6 = c("potato", "chips", "chips,potato", NA, NA))

你是这样的意思吗?我把你的NA值固定为合乎逻辑而不是字符。

#### Data Fix ####
library(tidyverse) # for mutate later
Dataframeexample <- data.frame(Q5 = c("potato", "chips", "chips",
"chips,potato","icecream,chips,potato",
"icecream,potato",
"chips", NA, NA))
#### Ifelse Statement ####
Dataframeexample %>% 
mutate(Q5 = ifelse(is.na(Q5),
0,
1))

给你这个数据:

Q5
1  1
2  1
3  1
4  1
5  1
6  1
7  1
8  0
9  0

编写一个函数来进行转换,并将其应用于数据集的字符列。下面的函数甚至适用于数据中存在的真正NA

na_falsetrue <- function(x, na.string = "NA") {
is.na(x) <- x == na.string
as.integer(!is.na(x))
}
i_char <- sapply(Dataframeexample, is.character)
Dataframeexample[i_char] <- lapply(Dataframeexample[i_char], na_falsetrue)
Dataframeexample
#>   Q5
#> 1  1
#> 2  1
#> 3  1
#> 4  1
#> 5  1
#> 6  1
#> 7  1
#> 8  0
#> 9  0

创建于2022-10-30,reprex v2.0.2

最新更新