【问题标题】:How to divide each value in a data frame by column total in R?如何将数据框中的每个值除以 R 中的列总数?
【发布时间】:2022-06-22 00:48:25
【问题描述】:

我使用代码

> df <- lapply(dane %>% select(starts_with("P_2_")),function(x) {factor(x,levels = 1:8)})
> data.frame(lapply(df,tabulate))

得到结果

  P_2_1 P_2_2

1   520   109

2   113    83

3   249   129

4    58    76

5    79   189

6    30   327

7     6   104

8    48    86

我应该在代码中进行哪些更改,以获得将数据框中的每个值除以列总数的附加列?

##     Odp            P_2_1         P_2_1             P_2_2          P_2_2
##   <dbl>            <int>          <dbl>            <int>          <dbl>
## 1     1              520          47.1               109           9.88
## 2     2              113          10.2                83           7.52
## 3     3              249          22.6               129          11.7 
## 4     4               58           5.26               76           6.89
## 5     5               79           7.16              189          17.1 
## 6     6               30           2.72              327          29.6 
## 7     7                6           0.54              104           9.43
## 8     8               48           4.35               86           7.8

【问题讨论】:

    标签: r


    【解决方案1】:

    除以colSumscbind

    cbind(df1, 100 * df1/colSums(df1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多