简体   繁体   中英

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

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 :

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 . 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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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