【问题标题】:R: Convert frequency to percentage with only a selected number of columnsR:仅使用选定的列数将频率转换为百分比
【发布时间】:2017-05-03 13:35:59
【问题描述】:

我想使用 dplyr 将填充频率的数据帧转换为按行填充百分比的数据帧。

我的数据集具有填充其他变量的特殊性,我只想计算由名称向量定义的一组列的百分比。另外,我想使用 dplyr 库。

sim_dat <- function() abs(floor(rnorm(26)*10))
df <- data.frame(a = letters, b = sim_dat(), c = sim_dat(), d = sim_dat()
                 , z = LETTERS)
names_to_transform <- names(df)[2:4]

df2 <- df %>%
  mutate(sum_freq_codpos = rowSums(.[names_to_transform])) %>%
  mutate_each(function(x) x / sum_freq_codpos, names_to_transform)
# does not work

知道怎么做吗?我已经尝试过 mutate_at 和 mutate_each 但我无法让它工作。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    你快到了!:

    df2 <- df %>%
      mutate(sum_freq_codpos = rowSums(.[names_to_transform])) %>%
      mutate_at(names_to_transform, funs(./sum_freq_codpos))
    

    . 大致翻译为“我在这里操作的对象”,在此调用中是“names_to_transform 中的焦点变量”。

    【讨论】:

      猜你喜欢
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多