7

我有一个因素在一个data frame水平像hot, warm, tepid, cold, very cold, freezing。我想将它们映射到一个整数列,其中的值在[-2, 2]回归范围内,其中一些值映射到同一事物。我希望能够指定显式映射,以便very hotwords 映射到2very coldwords 到-2等。我该如何干净地做到这一点?我想要一个函数,我只是将一些命名列表传递给,或者其他东西。

4

2 回答 2

16

假设因子向量x包含类别。

temperatures <- c("hot", "warm", "tepid", "cold", "very cold", "freezing")
set.seed(1)
x <- as.factor(sample(temperatures, 10, replace=TRUE))
x
[1] warm     tepid    cold     freezing warm     freezing freezing cold    
[9] cold     hot     
Levels: cold freezing hot tepid warm

temp.map使用映射创建一个数值向量。请注意,“热”和“暖”映射到下面的相同值。

temp.map <- c("hot"=2, "warm"=2, "tepid"=1, "cold"=0, "very cold"=-1, "freezing"=-1)    
y <- temp.map[as.character(x)]
y
warm    tepid     cold freezing     warm freezing freezing     cold 
   2        1        0       -1        2       -1       -1        0 
cold      hot 
   0        2 
于 2013-01-28T09:54:39.547 回答
7

使用 可以轻松地将因子转换为整数as.integer

例如:

>temperatures <- c("Hot", "Warm", "Tiepid", "Cold", "Very cold", "Freezing")
> set.seed(12345)
> a <- sample(temperatures, 10, r=T)
> a <- factor(a, levels = temperatures)
> a
 [1] Very cold Freezing  Very cold Freezing  Tiepid    Hot       Warm     
 [8] Cold      Very cold Freezing 
Levels: Hot Warm Tiepid Cold Very cold Freezing
> as.integer(a)
 [1] 5 6 5 6 3 1 2 4 5 6

如果你需要它在 [-2;2] 范围内,你会做

> as.integer(a)-3
  [1]  2  3  2  3  0 -2 -1  1  2  3
于 2013-01-28T06:51:51.820 回答