gpt4 book ai didi

r - 更改级别时如何保持 NA

转载 作者:行者123 更新时间:2023-12-05 06:39:01 25 4
gpt4 key购买 nike

我构建了一个包含 NA 的因子向量。

my_vec <- factor(c(NA,"a","b"),exclude=NULL)
levels(my_vec)
# [1] "a" "b" NA

我更改其中一个级别。

levels(my_vec)[levels(my_vec) == "b"] <- "c"

NA 消失。

levels(my_vec)
# [1] "a" "c"

我怎样才能保留它?


编辑

@rawr 提供了一个在大多数情况下都可以工作的很好的解决方案,它适用于我之前的具体示例,但不适用于我将在下面展示的那个@Hack-R 有一个使用 addNA 的实用选项,我可以让它工作,但我宁愿一个完全通用的解决方案

看到这个普遍的问题

my_vec <- factor(c(NA,"a","b1","b2"),levels = c("a",NA,"b1","b2"),exclude=NULL)
levels(my_vec)
[1] "a" NA "b1" "b2"
levels(my_vec)[levels(my_vec) %in% c("b1","b2")] <- "c"
levels(my_vec)
[1] "a" "c" # NA disppeared

@rawr 的解决方案:

my_vec <- factor(c(NA,"a","b1","b2"),levels = c("a",NA,"b1","b2"),exclude=NULL)
levels(my_vec)
[1] "a" NA "b1" "b2"
attr(my_vec, 'levels')[levels(my_vec) %in% c("b1","b2")] <- "c"
levels(my_vec)
droplevels(my_vec)
[1] "a" NA "c" "c" # c is duplicated

@Hack-R 的解决方案:

my_vec <- factor(c(NA,"a","b1","b2"),levels = c("a",NA,"b1","b2"),exclude=NULL)
levels(my_vec)
[1] "a" NA "b1" "b2"
levels(my_vec)[levels(my_vec) %in% c("b1","b2")] <- "c"
my_vec <- addNA(my_vec)
levels(my_vec)
[1] "a" "c" NA # NA is in the end

我想要 levels(my_vec) == c("a",NA,"c")

最佳答案

您必须引用 NA,否则 R 会将其视为空值而不是因子水平。默认情况下,因子级别按字母顺序排序,但显然这并不总是有用,因此您可以通过将新的列表顺序传递给 levels()

来指定不同的顺序
require(plyr)
my_vec <- factor(c("NA","a","b1","b2"))
vec2 <- revalue(my_vec,c("b1"="c","b2"="c"))

#now reorder levels

my_vec2 <- factor(vec2, levels(vec2)[c(1,3,2)])

Levels: a NA c

关于r - 更改级别时如何保持 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45216532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com