I'm looking for some help in defining a function to reverse code an ordinal variable. I'm using survey data in which theoretically related variables are coded in different directions i.e, perceptions of a concept are measured with several different variables, some of which denote higher values as "positive", others denote lower values as "positive". I've written a function that allows me to reverse code the selected variables so that they are consistently coded:
reverse_code <- function(x, df){
df[x] <- df[x] * -1 + max(df[x], na.rm = TRUE) + 1
return(df)
}
# call the function - note that var names need to be quoted, but not the dataframe
data <- reverse_code(c("var1", "var2", "var3", "var4"), data)
but it is sensitive to quotation marks as you see in my code comment above. The variable names need to be quoted, but not the dataframe. Any thoughts on how I could make this work so that it were insensitive to the inclusion/exclusion of quotation marks? I thought about including an if/else statement at the beginning to test for quotes, but I'm not sure how I would do this.
I realize that this function already assumes that the data have been cleaned of negative values, which for data that I typically use, almost exclusively denote missing values.
Edit:
As per a comment, to clarify, I would like for it to not matter if I called the function like this:
reverse_code(var1, data)
or like this:
reverse_code("var1", data)