【问题标题】:Add one proportion column for every column为每一列添加一个比例列
【发布时间】:2017-12-14 20:38:30
【问题描述】:

我有一个包含多列和多行的数据框,我的目标是为每一列添加一个新列,并在其后添加一个新列,该列占列总和的比例。

我有类似的东西:

a b c 
1 4 5 
8 2 3 
1 4 2

我正在尝试将其转换为:

a a.2 b b.2 c c.2
1 0.1 4 0.4 5 0.5 
8 0.8 2 0.2 3 0.3
1 0.1 4 0.4 2 0.2

但我想不出一种方法来在循环中命名add_column 中的这些新列。

到目前为止,我的代码如下:

j=1
while (j <= length(colnames(eleicao))) {
  i <- colnames(sample)[j]
  nam <- paste("prop", i, sep = ".")
  j=j+1
  sample <- add_column(sample, parse(nam) = as.list(sample[i]/colSums(sample[i]))[[1]] .after = i)
}

我总是遇到同样的问题:Error: Column 'nam' already exists

我怎样才能实现我的目标?我怎样才能让add_column 明白我正在尝试使用 'nam' 的 VALUE 来命名列?

【问题讨论】:

  • 请接受有助于解决您问题的答案

标签: r loops naming


【解决方案1】:

以下解决方案依赖于 tidyverse 中包含的dplyr

library(tidyverse)

df <- tibble(
  a = c(1, 8, 1),
  b = c(4, 2, 4),
  c = c(5, 3, 2)
)

df %>% 
  mutate_all(funs(prop = . / sum(.)))

返回

# A tibble: 3 x 6
      a     b     c a_prop b_prop c_prop
  <dbl> <dbl> <dbl>  <dbl>  <dbl>  <dbl>
1     1     4     5    0.1    0.4    0.5
2     8     2     3    0.8    0.2    0.3
3     1     4     2    0.1    0.4    0.2

【讨论】:

    【解决方案2】:

    有点草率的解决方案(使用apply):

    # Using OPs data stored in df
    res <- do.call(cbind, apply(df, 2, function(x) data.frame(x, y = x / sum(x))))
    #   a.x a.y b.x b.y c.x c.y
    # 1   1 0.1   4 0.4   5 0.5
    # 2   8 0.8   2 0.2   3 0.3
    # 3   1 0.1   4 0.4   2 0.2
    
    # Name
    colnames(res) <- sub(".x", "", sub(".y", ".2", names(res)))
    

    【讨论】:

      【解决方案3】:

      这是一个使用prop.table的选项

      cbind(df1, prop.table(as.matrix(df1), 2))[order(rep(names(df1), 2))]
      #  a a.1 b b.1 c c.1
      #1 1 0.1 4 0.4 5 0.5
      #2 8 0.8 2 0.2 3 0.3
      #3 1 0.1 4 0.4 2 0.2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-13
        • 1970-01-01
        • 2012-11-30
        • 1970-01-01
        • 2012-10-02
        • 1970-01-01
        • 2015-09-03
        • 1970-01-01
        相关资源
        最近更新 更多