2017-11-21 9 views
2
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")) 

私は、次の値既存の列の文字列

  • 0が割り当てられている

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

    をとる列weightを追加するに基づいて列を追加するときsatisfactionLevel =「非常に不満」 、

  • 1 satisfactionLevel = "非常に満足"の場合、
  • 0.75 w鶏満足度レベル= "満足"、
  • "どちらも満足でも不満でもない"場合0.5。 (case_when付き)

答えて

1

dplyrソリューション:あなたのweightScoresのデータフレームに "satisfactionLevel" の列が含まれている場合

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)) 
+0

エレガントなソリューションを使用することができるはずです、まさに私は望んでいた。 +1私から – Greconomist

+1

@Greconomist助けて幸せ:-) – PoGibas

0

、あなたは

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