根据现有列字符串添加列

时间:2017-11-21 23:20:42

标签: r dplyr

library(dplyr)

data <- data_frame(ended= c("14/11/2016 13:37", "14/11/2016 13:37",
"14/11/2016 13:47", "14/11/2016 13:51", "14/11/2016 13:51"), 
satisfactionLevel = c("Very dissatisfied", "Very satisfied",
"Satisfied", "Neither satisfied nor dissatisfied",
"Very satisfied"))

我想添加一列weight,其中包含以下值

weightScores <- data_frame(weight = c(0, 0.5, 0.75, 1))

其中

    当满意度=“非常不满意”时,分配
  • 0,
  • 1当满意度=“非常满意”时,
  • 0.75 whenancyLevel =“Satisfied”,
  • 0.5时“既不满意也不满意”。

2 个答案:

答案 0 :(得分:1)

dplyr解决方案(case_when):

library(dplyr)
# Using OPs data
data <- data %>%
    mutate(weight = case_when(
         satisfactionLevel == "Very dissatisfied" ~ 0,
         satisfactionLevel == "Very satisfied" ~ 1,
         satisfactionLevel == "Satisfied" ~ 0.75,
         satisfactionLevel == "Neither satisfied nor dissatisfied" ~ 0.5))

答案 1 :(得分:0)

如果您在weightScores数据框中包含“satisfactionLevel”列,则应该可以使用

merge(data, weightScores, by="satisfactionLevel")