# Calculate percent of column in R

You want to calculate percent of column in R as shown in this example, or as you would in a PivotTable:

Here are two ways: (1) using Base R and (2) using dplyr library.

``````fruits = data.frame(fruit = c('Apples','Bananas','Oranges','Mangoes','Pineapples','Watermelons','Canteloupes'),
weight = c(9,18,4,19,10,18,5),
cost = c(27,54,8,76,50,18,6.5))``````

### Doing it with Base R

``````fruits\$weight_pct = fruits\$weight / sum(fruits\$weight)
fruits\$cost_pct = fruits\$cost / sum(fruits\$cost)``````

We’re manually creating two columns using standard dollar sign notation.

### Doing it with dplyr

``````fruits = mutate(fruits,
weight_pct = weight / sum(weight),
cost_pct = cost / sum(cost))``````

Here we used the `mutate()`. This is my preferred method because (1) it’s simpler to type, (2) dplyr is great and you can string together more commands easily.

### Result: Percent of column

The above solutions result in this table:

```        fruit weight cost weight_pct   cost_pct
1      Apples      9 27.0 0.10843373 0.11273486
2     Bananas     18 54.0 0.21686747 0.22546973
3     Oranges      4  8.0 0.04819277 0.03340292
4     Mangoes     19 76.0 0.22891566 0.31732777
5  Pineapples     10 50.0 0.12048193 0.20876827
6 Watermelons     18 18.0 0.21686747 0.07515658
7 Canteloupes      5  6.5 0.06024096 0.02713987
```