简体   繁体   English

将 integer 数值转换为百分比

[英]Convert the integer numeric numbers into percentages

In an input data structure在输入数据结构中

data.frame(stockname = c("google", "amazon"), open= c(30, 40), close = c(32, 48))

How is it possible to convert the interger number which is existed in every row with the respectively percentage using as sum the full sum of all rows of the data frame to calculate the percentage.如何使用数据框所有行的总和来计算百分比,如何将每行中存在的整数转换为相应的百分比。

The total sum of all rows of the input data is 150 so the percentage example output data frame is输入数据的所有行的总和为 150,因此百分比示例 output 数据帧为

data.frame(stockname = c("google", "amazon"), open= c(20%, 26.7%), close = c(21.3%, 32%))

Perhaps this is what you are after也许这就是你所追求的

df[-1] <- df[-1] / sum(df[-1])

which gives这使

> df
  stockname      open     close
1    google 0.2000000 0.2133333
2    amazon 0.2666667 0.3200000

This can be done using prop.table :这可以使用prop.table来完成:

df[-1] <- prop.table(df[-1])
df
#   stockname      open     close
# 1    google 0.2000000 0.2133333
# 2    amazon 0.2666667 0.3200000

If you're interested in formatting the output as well, look at sprintf .如果您也对格式化 output 感兴趣,请查看sprintf Starting with the source data again, try:再次从源数据开始,尝试:

df[-1] <- sprintf("%.1f%%", unlist(prop.table(df[-1])) * 100)
df
#   stockname  open close
# 1    google 20.0% 21.3%
# 2    amazon 26.7% 32.0%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM