R bin非数值

时间:2015-11-20 13:43:00

标签: r

我知道我可以使用cut来合并数值。我想bin非数字值。考虑一下这个数据框:

color <- c("Red","Blue","Green","Gray","Black")
dataframe <- data.frame(id,color)

我想创建一个如下所示的数据框:

 id  color Group
  1    Red  R
  2   Blue  B
  3  Green  G
  4   Gray  G  
  5  Black  B

我可以创建一个函数并调用lapply。是否有一个预先构建的函数已经为我传递了条件表达式?

1 个答案:

答案 0 :(得分:2)

这是将值映射到新的分箱值的一种方法。

color <- c("Red","Blue","Green","Gray","Black")
dataframe <- data.frame(id = 1:5, color)

library(plyr)

dataframe$Group <- mapvalues(dataframe$color, from = c("Red","Blue","Green","Gray","Black"), 
                                              to = c("R", "B", "G", "G", "B"))

  id color Group
1  1   Red     R
2  2  Blue     B
3  3 Green     G
4  4  Gray     G
5  5 Black     B