Add a new column to a dataframe with the percentage of every value of this dataframe

Viewed 3034

I have the dataframe below and I would like to add a new column with the percentage of every value of this dataframe. Something like:

name <- c("asdad","dssdd")
number <- c(5,5)
df <- data.frame(name,number)

for (i in 1:nrow(df)) {
  percentage<-df[i,1]/sum(df$number)
}

new <- cbind(df, percentage)

but I get NAs instead of percentages.

2 Answers

As mentioned in the comments, below is the solution.

library(dplyr)
df %>% mutate(Percentage = number/sum(number))

Output:
   name number Percentage
1 asdad      5       0.25
2 dssdd      5       0.25
3  assa     10       0.50

Why are you looping? Furthermore, why are you changing a single variable and then trying to bind it like a vector?

A much easier way to do this is to just add a column, i.e. df$percentage <- df$number/sum(df$number)*100

Related