0

我有一个 data.frame

df <- data.frame(Equip = c(1,1,1,1,1,2,2,2,2,2),
                 Notif = c(1,1,1,5,5,3,3,3,3,4),
                 Component = c("1","1","1","2","2","1","2","2","2","3"))

Notif被分类到Component列中的位置(因为它可能不相关,我不会展示我是如何创建该列的。)

现在我有一个将Notif值映射到相应类别的表:

 example <- 1 "repair" ; 3 "service" ; 4 "other" ; 5 "service"   

如何创建Category向量并将其添加到我的 data.frame?

4

1 回答 1

2

一种方法是使用命名向量映射NotifCategory

categories <- c(`1` = "repair", `3` = "service", `4` = "other",  `5` = "service")

然后你可以这样做:

df$Category <- categories[as.character(df$Notif)]

或等效地

df <- transform(df, Category = categories[as.character(Notif)])

在这两种情况下,输出都是:

df
#    Equip Notif Component Category
# 1      1     1         1   repair
# 2      1     1         1   repair
# 3      1     1         1   repair
# 4      1     5         2  service
# 5      1     5         2  service
# 6      2     3         1  service
# 7      2     3         2  service
# 8      2     3         2  service
# 9      2     3         2  service
# 10     2     4         3    other

另一种方法是合并 data.frames,比如数据库连接:

categories <- data.frame(Notif = c(1, 3, 4, 5),
                         Category = c("repair", "service", "other", "service"))

merge(df, categories, by = "Notif", all.x = TRUE)
#    Notif Equip Component Category
# 1      1     1         1   repair
# 2      1     1         1   repair
# 3      1     1         1   repair
# 4      3     2         1  service
# 5      3     2         2  service
# 6      3     2         2  service
# 7      3     2         2  service
# 8      4     2         3    other
# 9      5     1         2  service
# 10     5     1         2  service

请注意,输出已重新排序,Notif这对您来说可能是也可能不是问题。当Notif映射到多个变量(如Category.

于 2013-01-08T11:45:31.790 回答