【问题标题】:Hos can I add a column porcentaje based on other column in my data frame?如何根据数据框中的另一列添加列百分比?
【发布时间】:2021-12-26 03:01:43
【问题描述】:

我想在我的数据框中创建一个列,给出每个类别的百分比。总数 (100%) 将是列 Score 的摘要。

我的数据看起来像

Client  Score
  <chr> <int>
1 RP      125
2 DM      30

预期

Client  Score    %
  <chr> <int>
1 RP      125    80.6
2 DM      30     19.3

谢谢!

【问题讨论】:

    标签: r percentage mutated


    【解决方案1】:

    注意列名中的特殊字符不好。

    library(dplyr)
    df %>% 
      mutate(`%` = round(Score/sum(Score, na.rm = TRUE)*100, 1))
    
      Client Score    %
    1     RP   125 80.6
    2     DM    30 19.4
    

    【讨论】:

      【解决方案2】:

      可能最好的方法是使用 dplyr。我在下面重新创建了您的数据,并使用 mutate 函数在数据框上创建了一个新列。

      #Creation of data
      Client <- c("RP","DM")
      Score <- c(125,30)
      DF <- data.frame(Client,Score)
      DF
      
      #install.packages("dplyr") #Remove first # and install if library doesn't load
      library(dplyr)  #If this doesn't run, install library using code above.
      
      #Shows new column
      DF %>% 
        mutate("%" = round((Score/sum(Score))*100,1))
      
      #Overwrites dataframe with new column added
      DF %>% 
        mutate("%" = round((Score/sum(Score))*100,1)) -> DF
      

      使用基本 R 函数可以实现相同的目标。

      X <- round((DF$Score/sum(DF$Score))*100,1) #Creation of percentage
      DF$"%" <- X #Storage of X as % to dataframe
      DF #Check to see it exists
      

      【讨论】:

        【解决方案3】:

        base R,可以使用proportions

        df[["%"]] <-  round(proportions(df$Score) * 100, 1)
        

        -输出

        > df
          Client Score    %
        1     RP   125 80.6
        2     DM    30 19.4
        

        【讨论】:

        • @TarJae 我在那里看到了一些像弗兰克这样的传奇人物。使用他们的建议可能会更好
        • 好的,谢谢楼主!
        猜你喜欢
        • 2017-09-02
        • 2021-06-25
        • 2017-09-04
        • 2021-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多