Oposum
Oposum

Reputation: 1243

Changing proportion table values into percentages

I have the following table code

weather<-cbind(c(rep("rain",50),rep("sun",70),rep("rain",100),rep("sun",80)))
prop.table(table(weather))

...which results in the following output:

rain  sun 
 0.5  0.5 

How can I change the code so that the output instead becomes this:

rain  sun 
 50%  50%

Any suggestions?

Upvotes: 1

Views: 975

Answers (2)

cpander
cpander

Reputation: 374

You can use sprintf for this. In your example, you would do this:

sprintf("%2d%%", prop.table(table(weather))*100)

For more number format options, check out the sprintf documentation here.

Upvotes: 2

eipi10
eipi10

Reputation: 93761

paste0(round(prop.table(table(weather))*100, 1),'%')

round isn't necessary here, but it would be if your values had lots of decimal places.

Upvotes: 2

Related Questions