如何根据数据框中的另一列添加一列 porcentaje?

Hos can I add a column porcentaje based on other column in my data frame?

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

我的数据看起来像

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

预计

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

谢谢!

最好的方法可能是使用 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

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

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

base R中,可以使用proportions

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

-输出

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