Home > database >  Working out a column value based on another column as a percentage value
Working out a column value based on another column as a percentage value

Time:11-02

I am trying to create a new column which is a calculation between 2 other columns in my df, one column if a value and the other column if the % of the first column i wish to appear in my new column. Should be a bit easier to explain with my data;

df
   Country_Name           gdp_per_capita    Agriculture_GDP% 

 1 Albania                         3281.               20.6                          
 2 Algeria                         3515.               9.86                                     
 3 Bosnia and Herzegovina          3828.               8.21                                     
 4 Croatia                        11285.               3.90                                     
 5 Cyprus                         24686.               2.60

So I want to create a new column with the value for Albania to be 20.6% of 3281 here which would be 675.8

I had an attempt at this my dividing the 1st column by the second but it gave me some wrong results;

df$gdp_per_capita_agg_percen = df$gdp_per_capita/bar_df$Agriculture_GDP%

CodePudding user response:

It would be

 df$gdp_per_capita_agg_percen <- with(df, gdp_per_capita* 
               `Agriculture_GDP%`/100)

-output

> df
            Country_Name gdp_per_capita Agriculture_GDP% gdp_per_capita_agg_percen
1                Albania           3281            20.60                  675.8860
2                Algeria           3515             9.86                  346.5790
3 Bosnia and Herzegovina           3828             8.21                  314.2788
4                Croatia          11285             3.90                  440.1150
5                 Cyprus          24686             2.60                  641.8360

data

df <- structure(list(Country_Name = c("Albania", "Algeria", "Bosnia and Herzegovina", 
"Croatia", "Cyprus"), gdp_per_capita = c(3281, 3515, 3828, 11285, 
24686), `Agriculture_GDP%` = c(20.6, 9.86, 8.21, 3.9, 2.6)), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

CodePudding user response:

To get the correct calculation you need to do:

df$gdp_per_capita_agg_percen <- df$gdp_per_capita * df$Agriculture_GDP% / 100`

The issue is that to get the total value from a percent you need to multiply rather than divide.

  •  Tags:  
  • r
  • Related