Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change value to percentage of row in R [duplicate]

Tags:

r

percentage

this is my data

  A B C
A 9 1 0 
B 2 2 2
C 3 3 3

I want to get percentage of each row

my expect data is

     A    B    C
A  0.9  0.1    0 
B 0.33 0.33 0.33
C 0.33 0.33 0.33

I made my data with 'dcast' and there is column name on A,B and C. so actually my real data is

  Name    A    B    C
1    A  0.9  0.1    0 
2    B 0.33 0.33 0.33
3    C 0.33 0.33 0.33
like image 361
DK2 Avatar asked Jul 26 '15 14:07

DK2


People also ask

How do I convert a number to a percentage in R?

To calculate percent, we need to divide the counts by the count sums for each sample, and then multiply by 100. This can also be done using the function decostand from the vegan package with method = "total" .

How do I make a percentage row?

Row Percentages. "Row percentage" indicates the proportion of students represented in the table cell—that is, the number of students represented in a particular cell of the table, divided by the number of students in the row of the table, converted to a percentage.

How do I find the percentage of a data set in R?

To find the percentage of missing values in each column of an R data frame, we can use colMeans function with is.na function. This will find the mean of missing values in each column. After that we can multiply the output with 100 to get the percentage.


1 Answers

Seems a fair case for

df/rowSums(df)
#           A         B         C
# A 0.9000000 0.1000000 0.0000000
# B 0.3333333 0.3333333 0.3333333
# C 0.3333333 0.3333333 0.3333333

If you don't want so many digits after the dot set options(digits = 2) or use print(df/rowSums(df), digits = 2) or use round

round(df/rowSums(df), 2)
#      A    B    C
# A 0.90 0.10 0.00
# B 0.33 0.33 0.33
# C 0.33 0.33 0.33

Or as suggested by @akrun

round(prop.table(as.matrix(df1),1),2)
like image 165
David Arenburg Avatar answered Sep 17 '22 23:09

David Arenburg