As a big fan of dplyr and its tidy data concept, I would like to mutate a specific variable whenever it exists in a dataframe. This is the idea:
# Load libraries
library(dplyr)
# Create data frames
df1 <- data.frame(year = 2000:2010, foo = 0:10)
df2 <- data.frame(year = 2000:2010)
# Create function
cnd_mtt <- function(df){
df %>%
mutate_if(colname == "foo", as.factor) # <---- this is the tricky part
}
Expected result: the function should work for both data frames and without error
Ideas?
colname
? – MKRif
statement:if("foo" in names(df)) ...
– Gregor Thomas%in%
, see my answer – 3pitt