'Input column name as variable in a function

I'm trying to write a function that I can use across multiple dataframes which accepts column names as input. The objective is to identify whether an event happened (if it was the earliest) and then code the results into a binary 0 and 1. This is what I've come up with so far:

event <- function(x){
  analysis$event <- 0
  analysis$event[analysis$earliest == analysis$x] <- 1
}

However, when I try it with say test <- event(death_date) it returns just a value of 1. What went wrong and how can I fix it? Thanks!

r


Solution 1:[1]

The dollar operator does not work with variables. You can use double square brackets instead:

col_name <- "mpg"
mtcars[[col_name]]

# compare:
mtcars$mpg

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AEF