0

Im tryin to make a simple function where I have three possible arguments ("sun", "rain" or "wind") and the function should return the three months mean of chosen one.

rows <- c("april", "may", "june")
sun <- c(11,13,18)
rain <- c(8,7,5)
wind <- c(11,8,4)

table <- data.frame(sun=sun, rain=rain,wind=wind, row.names=rows)

function(argument){

sun <- table$sun
rain <- table$rain
wind <- table$wind

x <- mean(argument)
paste(x)
}

For example function("sun") should return 14.

The problem is that I understand how to link the argument to the column that includes the values.

1 Answers1

1

If you want to pass quoted argument to the funciton, you can subset the column using [[

get_mean_of_column <- function(data, column){
  mean(data[[column]], na.rm = TRUE)
}

get_mean_of_column(df, "sun")
#[1] 14

get_mean_of_column(df, "rain")
#[1] 6.66667

get_mean_of_column(df, "wind")
#[1] 7.66667

data

rows <- c("april", "may", "june")
sun <- c(11,13,18)
rain <- c(8,7,5)
wind <- c(11,8,4)
df <- data.frame(sun=sun, rain=rain,wind=wind, row.names=rows)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213