0

My dataframe named Vietnamese_age is like this:

  • Vietnamese_city: Hanoi Danang HCMcity ...
  • Age_population_from 10_to_20: 10000 20000 15000 ...
  • Age_population_from 20_to_30: 15000 25000 15000 ...
  • Age_population_from 30_to_40: 14000 28000 14000 ...
  • Age_population_from 40_to_50: 21000 26000 12000 ... and so on

There are too many of age period, so I'm going to make a function which has a string variable, so when i insert a certain string ("Age population from 10 - 20"), it will show the boxplot of this age group in certain city and the mean of whole country.

I have built the very first function:

Age_function <- function(x) { mean(Vietnamese_age$x) }

and tried:

x = "Age_population_from 10_to_20"

resulting in the following error:

Error in Age_function(Age_population_from 10_to_20) : object 'Age_population_from 10_to_20' not found

What should I do to solve this problem?

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • Welcome to SO. Please include a sample of your data try `dput(Vietnamese_age)` or a representative subset to make you question a [reprex]. – Peter May 06 '20 at 16:05

1 Answers1

0

Instead of using $, we can use [[

Age_function <- function(x) mean(Vietnamese_age[[x]], na.rm = TRUE)

It is also better to provide data as argument

Age_function <- function(dat, x) mean(dat[[x]], na.rm = TRUE)

and then call

Age_function(Vienamese_age,  "Age_population_from 10_to_20")
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you for the answer. I made it. But how can I filter the name of the city. It means function (dat, x,y) when y is the name of the Vietnamese city. It seems that i can't use: dat %>% filter ( Vietnamese_city == y). Is there any alternative way? Thank you! – Lê Quốc Khang Apr 28 '20 at 03:01