将两个响应合二为一
Putting two responses in one
我试图从调查数据中总结对问题的回答,许多问题的答案记录为999或998,分别表示"Don't know"和"Refused to answer"。我试图将这两个分类在一个标题下 ("No information"),并为其指定编号 -999。我不确定如何进行。
这是一种使用 dplyr 将数据帧所有列中的所有 998
和 999
更改为 -999
的方法。假设 998
和 999
不用作数据中的 "normal" 数字,而仅用于指示缺失值。但调查数据通常是这样。
# These libraries is needed
library(dplyr)
library(car) # not necessary to call, but has to be installed
# Some test data
data <- data.frame(a = c(1:10, 998),
b = c(21:31),
c = c(999,31:40))
# a predicate function which checks if a column x contains 998 or 999
check_998_999 <- function (x) {
any(x == 998) | any(x == 999)
}
# change all columns with 998 or 999 so that they become -999
data %>%
mutate_if(check_998_999,
~ car::recode(.x, "c(998,999) = -999"))
我更喜欢 car::recode
而不是 dplyr::recode
,因为您必须不那么具体,并且可以重新编码不同 class 的元素。例如,以上甚至在列为字符时也有效。
data <- data.frame(a = c(1:10, 998),
b = c(21:31),
c = c("999",letters[1:10]),
stringsAsFactors = F)
data %>%
mutate_if(check_998_999,
~ car::recode(.x, "c(998,999) = -999"))
我试图从调查数据中总结对问题的回答,许多问题的答案记录为999或998,分别表示"Don't know"和"Refused to answer"。我试图将这两个分类在一个标题下 ("No information"),并为其指定编号 -999。我不确定如何进行。
这是一种使用 dplyr 将数据帧所有列中的所有 998
和 999
更改为 -999
的方法。假设 998
和 999
不用作数据中的 "normal" 数字,而仅用于指示缺失值。但调查数据通常是这样。
# These libraries is needed
library(dplyr)
library(car) # not necessary to call, but has to be installed
# Some test data
data <- data.frame(a = c(1:10, 998),
b = c(21:31),
c = c(999,31:40))
# a predicate function which checks if a column x contains 998 or 999
check_998_999 <- function (x) {
any(x == 998) | any(x == 999)
}
# change all columns with 998 or 999 so that they become -999
data %>%
mutate_if(check_998_999,
~ car::recode(.x, "c(998,999) = -999"))
我更喜欢 car::recode
而不是 dplyr::recode
,因为您必须不那么具体,并且可以重新编码不同 class 的元素。例如,以上甚至在列为字符时也有效。
data <- data.frame(a = c(1:10, 998),
b = c(21:31),
c = c("999",letters[1:10]),
stringsAsFactors = F)
data %>%
mutate_if(check_998_999,
~ car::recode(.x, "c(998,999) = -999"))