【问题标题】:How to create a factor with specified levels and labels, change the levels and adapt the labels step by step如何创建具有指定级别和标签的因子,更改级别并逐步调整标签
【发布时间】:2020-01-15 05:57:17
【问题描述】:

我想一步一步做三件事,不幸的是我被卡住了。也许有人可以引导我完成 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,并分配有标签“yes”(表示 1)和“no”(表示 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,但仍然分配了原始标签“yes”(对于 1)和“no”(对于 2)。

所以在第三步中,我想调整值标签,使“否”对应于值 0,而不是两个(不再存在)值 2。我该怎么做?

这应该是一个社区维基吗?

【问题讨论】:

  • 恐怕一旦你有一个factor 和不同的labels,你就无法取回原来的值。这个stackoverflow.com/questions/39779688/… 看起来是一个类似的问题,但没有答案。
  • @RonakShah 好的,但我确信可以创建一个取值为 1 或 2 的因子,并指定 1 代表“label_a”,2 代表“label_b”。因此,如果您更改变量值,例如从 {1,0} 更改为 {1,2},也应该可以分配新标签,对吧?

标签: r variables label levels


【解决方案1】:

正如 cmets 中提到的,一旦我们拥有 factorlabels,我们就会失去初始值。我们可以尝试将数据存储在命名向量或列表中

#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 

【讨论】:

    猜你喜欢
    • 2013-10-24
    • 2013-06-14
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    相关资源
    最近更新 更多