我想一步一步做三件事,不幸的是我卡住了。也许有人可以引导我完成 R 中的过程或指出我的错误。
# Create a dataset containing a factor with pre-defined levels and labels
testdat<-data.frame(a=factor(c(1,2), labels=c("yes","no")))
我期望得到一个名为“a”的因子,它取值 1 和 2,并分配标签"is"(代表 1)和“否”(代表 2)。不幸的是,该因子现在只包含我指定为标签的内容,但 c(1,2) 不再可访问。
# Next, I would like to assign new levels to the factor, namely {1,0} instead of {1,2}
testdat$a[testdat==2] <- 0
显然这行不通,因为第一步的问题,因为没有值==2
。但理想情况下,在这第二步之后,我会有一个变量“a”,它现在取值 1 和 0,但仍然分配了原始标签"is"(对于 1)和“否”(对于 2)。
因此,在第三步中,我想调整值标签,使“否”对应于值 0,而不是两个(不再存在)值 2。我该怎么做?
这应该是一个社区 wiki 吗?
最佳答案
正如评论中提到的,一旦我们有了带有 labels
的 factor
,我们就会失去初始值。我们可以尝试将数据存储在命名向量或列表中
#Label can be considered as name of the vector
a <- c(yes = 1, no = 2)
#We can now change the value where a == 2 to 0 and labels are still intact
a[a == 2] <- 0
a
#yes no
# 1 0
关于r - 如何创建具有指定级别和标签的因子,逐步更改级别和调整标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57922241/