【问题标题】:R: How are factor labels mapped to the correct values in a data.frame?R:因子标签如何映射到 data.frame 中的正确值?
【发布时间】:2018-04-04 17:18:16
【问题描述】:

编辑:包括我对我仍然不清楚的文档的阅读

我是 R 新手,正在使用预加载的 RStudio mtcars data.frame。我正在将 cyl 变量转换为因子并标记它们。我的代码是:

df <- mtcars
str(df)
df$cyl <- factor(df$cyl, labels = c('Four cylinder', 'Six Cylinder', 'Eight Cylinder'))
str(df)

哪些输出:

> df <- mtcars
> str(df)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
> df$cyl <- factor(df$cyl, labels = c('Four cylinder', 'Six Cylinder', 'Eight Cylinder'))
> str(df)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : Factor w/ 3 levels "Four cylinder",..: 2 2 1 2 3 2 3 1 1 2 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

我的问题是:factor 代码部分如何正确分配标签(即'Four cylinder',在转换后表示为1,正确分配了@987654331 @s 在原来的df)。它是否只是按升序应用标签作为默认行为?如果我有一个字段,例如,我想将 10 个唯一值转换为因子,该怎么办。如何确定我的标签和替换值与正确的原始值相对应?

?factor 访问的文档指出:

levels:x 可能采用的值(作为字符串)的可选向量。默认是 as.character(x) 采用的唯一值集,按 x 升序排序。

这似乎表明标签将按原始变量值升序应用,但我只是想确保我理解正确。

【问题讨论】:

  • 这个链接很好地解释了因子的工作原理simplystatistics.org/2015/07/24/…
  • 这有助于理解 stringsAsFactors = TRUE 的默认行为,但不能回答我关于 factor 以及它如何将标签应用于预期值的问题
  • 一位同事给我发了THIS:我相信它回答了这个问题。我将阅读它,然后回答我自己的问题,这样做是否合适?
  • 因素的行为是stringsAsFactors = TRUE默认行为的原因。从第 8 段“还有一个更晦涩的原因。”开始,文章描述了如何使用整数来有效地引用字符值以节省内存空间。

标签: r dataframe


【解决方案1】:

在这个例子中它知道,因为它将 mtcars$cyl 中的数值转换为字符向量c(4, 6, 8, 6, ...) -&gt; c("4", "6", "8", ...),所以通过字母数字排序('4' 然后 '6',然后 '8'; 因为你在您对factor 的调用中未指定levels),则通过将valueslevels 匹配来找到存储在df$cyl 中的数值。标签并不会真正影响因子排序:您可以反常地将标签“六缸”与级别“4”匹配。

as.numeric(因子(c(4, 6, 8, 6, 6, 4))) [1] 1 2 3 2 2 1

【讨论】:

  • 通过字母数字排序得到它 - 这就是我根据文档所怀疑的。你能澄清一下我如何将标签“六缸”与“4”级匹配(顺便说一句,这里的水平是正确的词吗?还是它的价值)?
  • 这里我们给级别“4”贴上标签“五个汽缸?”和其他各种变态:factor(c(6, 4, 8), labels = c("five cylinders?", "four cylinders?", "three cylinders")) [1] four cylinders? five cylinders? three cylinders Levels: five cylinders? four cylinders? three cylinders
  • 啊,呃。非常感谢 - 作为一个新程序员,我知道这些东西对你来说可能听起来很愚蠢,但它对我的理解非常有帮助。
猜你喜欢
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 2017-11-11
  • 2016-05-23
  • 2016-05-04
  • 2022-01-16
  • 1970-01-01
相关资源
最近更新 更多