在表格和申请之后,我该如何分配它

时间:2013-01-08 11:37:01

标签: r dataframe

我有一个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"   

如何在我的data.frame中创建和添加Category向量?

1 个答案:

答案 0 :(得分:2)

一种方法是使用命名向量将Notif映射到Category

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

)时,此方法特别有用