r-我可以在数据帧中的其他列的基础上添加一个列porcentaje吗



我想在我的数据框架中创建一列,给出每个类别的百分比。总数(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

谢谢!

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

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

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

base R中,可以使用proportions

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

-输出

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

最新更新