我试着从carData包中改变WVS数据集的变量值,但出现了一个错误。
Error in `$<-.data.frame`(`*tmp*`, religion, value = c(2L, 2L, 2L, 2L, :
replacement has 5383 rows, data has 5381
In addition: Warning message:
In `[<-.factor`(`*tmp*`, c("yes", "no"), value = c(2L, 2L, 2L, 2L, :
invalid factor level, NA generated
宗教信仰是一个因子变量,它应该仍然是因子。
这是我的代码
data(WVS)
head(WVS)
WVS$religion[c("yes","no")] <- c("oui", "non")
你可以用 dplyr
:
library(dplyr)
WVS <- WVS %>% mutate(religion = if_else("yes","oui","non"))
如果你的变量可以有更多的选项,你不想搞乱,你可以使用 case_when
:
WVS <- WVS %>%
mutate(religion = case_when(religion == "yes" ~ "oui",
religion == "no" ~ "non",
TRUE ~ religion))
您可以使用 重新编码 与因素变量
WVS <- WVS %>%
mutate(religion = recode(religion,
yes = "oui",
no = "non"))