【发布时间】:2015-02-12 02:26:51
【问题描述】:
如果我想在 R 中获得一个因子的数值,我已经厌倦了写 as.numeric(as.character(my.factor))。虽然它有效,但代码的作用并不是不言而喻的,只是感觉转换数字是错误的到字符串并再次返回以对它们进行任何操作。有没有像factor.values(my.factor) 这样更简单、更不言自明的方式?
建议将其打包在自定义函数中,例如
factor.values = function(x) as.numeric(levels(x))[x] # get the actual values of a factor with numeric labels
这个解决方案的问题是,如果它要被协作者重现,它必须在脚本之间复制粘贴。我在问是否有一个简短的内置方法可以做到这一点。我知道这是一个非常小的问题,但由于它很常见,而且很多人认为通常提出的解决方案违反直觉,所以我还是提出来了。
问题
Fpr 联合起来,如果你有一个因子并且想要对它进行数值运算,你会遇到很多问题:
> my.factor = factor(c(1, 1, 2, 5, 8, 13, 21))
> sum(my.factor) # let's try a numeric operation
Error in Summary.factor(1:6, na.rm = FALSE) :
sum not meaningful for factors
> as.numeric(my.factor) # oh, let's make it numeric then.
[1] 1 1 2 3 4 5 6 # argh! levels numbers and not values
> as.character(my.factor) # because the web told me so.
[1] "1" "1" "2" "5" "8" "13" "21" # closer...
> as.numeric(as.character(my.factor)) # NOT short or self-explanatory!
[1] 1 1 2 5 8 13 21 # finally we can sum ...
> sum(as.numeric(as.character(my.factor)))
[1] 51
【问题讨论】:
-
根据我的经验,只有在数据导入出现问题时才需要这样做。解决方案通常是修复导入步骤。数字信息不应该是一个开始的因素。
-
没错,但诸如
mapvalues之类的方便函数会无缘无故地从数字数据中提取因子。所以我经常发现自己在使用它。 -
只需围绕“丑陋”的代码编写一个简单的包装函数并完成它。自己动手真的没什么大不了的。
-
你能举一个
mapvalues“无缘无故地从数字数据中提取因子”的例子吗? -
不使用因子更简单(对我来说),但如果你已经拥有它们,这里是 plyr 的替代方法:
df.target$x <- with(df.source, setNames(x, id))[as.character(df.target$id)]。这是另一个:m <- merge(df.source, df.target, by="id", sort=FALSE); m[order(m$id),]