【问题标题】:How to mutate a column containing the factor for each feature in dataframe?如何改变包含数据框中每个特征的因子的列?
【发布时间】:2018-11-28 14:29:44
【问题描述】:

我有一个数据集,基本上是 PHQ-9 问卷的回复。其中有 9 列具有“根本没有”、“有时”、“几天”、“超过一半的天”、“几乎每天”的因素。得分分别为 0、1、1、2、3。 对所有 9 个问题的回答最终给出了 PHQ 分数(满分 27)。

在我的数据集中,我对这些问题的回答存储为:

$ 利息:因子 w/ 5 个级别“超过一半的天数”,..:1 4 2 2 4 5 4 4 4 5 ...

现在我真正想要的是与上述每个特征相邻的另一列,其中包含相应的分数。此外,最后我想在最后使用这些因素分数来计算结果,以给出抑郁分数。

这是我正在查看的输出:

Interest    I_Factor Pleasure        P_factor  Score 
Not at all    0      Nearly Everyday  2          2

【问题讨论】:

  • 请展示一个可重现的小例子和预期的输出
  • 你可以在R中使用recode函数
  • @Hunaidkhan recode 函数不会覆盖值吗?
  • @PrajwalKharel 在新列中重新编码而不是更改相同的列

标签: r


【解决方案1】:

为您创建模拟数据框:

df <- data.frame(id = c("001", "002", "003", "004", "005"),
             PHQ_1 = c("Not at all", "Not at all", "Sometimes", "Sometimes", "Several Days"),
             PHQ_2 = c("Sometimes", "Sometimes", "Several Days", "More than half the days", "Nearly everyday"))

使用mutate_at 为您选择问卷项目,然后从psych 包中批量应用recode 以将李克特量表从因子更改为数字。为新列提供“名称”,它们不会替换旧列(例如,下面示例中的“numeric_columns”)。

完成后,再次使用mutate 计算行总和并将其放入新列。

library(dplyr)
library(psych)

test <- df %>%
  mutate_at(vars(PHQ_1:PHQ_2), funs(numeric_columns = recode(., 
                                       "Not at all" = 0,
                                       "Sometimes" = 1,
                                       "Several Days" = 1,
                                       "More than half the days" = 2,
                                       "Nearly everyday" = 3))) %>%
  mutate(total = rowSums(select(., contains("numeric_columns"))))

示例输出如下。原始列被保留,您拥有数字格式的新列以及问卷的总分。

   id        PHQ_1                   PHQ_2 PHQ_1_numeric_columns PHQ_2_numeric_columns total
1 001   Not at all               Sometimes                     0                     1     1
2 002   Not at all               Sometimes                     0                     1     1
3 003    Sometimes            Several Days                     1                     1     2
4 004    Sometimes More than half the days                     1                     2     3
5 005 Several Days         Nearly everyday                     1                     3     4

【讨论】:

    猜你喜欢
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多