当我使用casewhen()和mutate()时,没有将新变量保存在 Dataframe 中[重复]

42fyovps  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(127)
    • 此问题在此处已有答案**:

mutate function is not updating(3个答案)
2天前关闭。
我可能用错了,但是当我使用下面的代码时,它只打印了一个总结语句。有没有办法把这个输出保存在一个新的变量中?

data %>%
mutate(motivation = case_when(DRG_WHY_TRY == 1 ~ 'experimentation'
,DRG_WHY_SLP == 1 ~ 'cope'
,DRG_WHY_RLX == 1 ~ 'cope'
,DRG_WHY_PAN == 1 ~ 'medical'
,DRG_WHY_NTH == 1 ~ 'bored'
,DRG_WHY_NCN == 1 ~ 'no conseq'
,DRG_WHY_MED == 1 ~ 'medical'
,DRG_WHY_HIG == 1 ~ 'enhancement'
,DRG_WHY_FUN == 1 ~ 'social'
,DRG_WHY_FRD == 1 ~ 'conformity'
,DRG_WHY_FGT == 1 ~ 'cope'
,DRG_WHY_FEL == 1 ~ 'enhancement'
,DRG_WHY_ANX == 1 ~ 'cope'
,TRUE ~ 'else'))
r7knjye2

r7knjye21#

正如注解所述,需要使用赋值操作符<-将其保存为新变量,管道操作符只是将数据集传递过去,而不保存修改后的结果。

data <- data %>%
mutate(motivation = case_when(DRG_WHY_TRY == 1 ~ 'experimentation'
,DRG_WHY_SLP == 1 ~ 'cope'
,DRG_WHY_RLX == 1 ~ 'cope'
,DRG_WHY_PAN == 1 ~ 'medical'
,DRG_WHY_NTH == 1 ~ 'bored'
,DRG_WHY_NCN == 1 ~ 'no conseq'
,DRG_WHY_MED == 1 ~ 'medical'
,DRG_WHY_HIG == 1 ~ 'enhancement'
,DRG_WHY_FUN == 1 ~ 'social'
,DRG_WHY_FRD == 1 ~ 'conformity'
,DRG_WHY_FGT == 1 ~ 'cope'
,DRG_WHY_FEL == 1 ~ 'enhancement'
,DRG_WHY_ANX == 1 ~ 'cope'
,TRUE ~ 'else'))

相关问题