I have a dataframe called df:
df <- data.frame(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
customer = c("Alice", "Bob", "Carlos", "Chuck", "Craig", "Heidi", "Judy", "Rupert", "Wendy"),
Balance = c(100, 75, 56, 172, 450, 777, 1001, 25, 968),
Hour = c(1, 23, 4, 5, 6, 12, 14, 17, 17),
InDebt = c(1, 1, 1, 1, 0, 0, 0, 1, 1),
DueDay = c("Mon", "Tue", "Wed", "Fri", "Sun", "Sat", "Thu", "Mon", "Wed"),
AppBooked = c(1, 1, 1, 0, 0, 1, 0, 1, 1)
)
I want to convert certain columns (in this instance Hour, InDebt, AppBooked) to factors and at present have been using the following method:
df$Hour <- as.factor(df$Hour)
df$InDebt <- as.factor(df$InDebt)
df$AppBooked <- as.factor(df$AppBooked)
Although this works, I wanted to see if there was a quicker way of doing this (particularly if I have to do it for 100 different column names). I'm basically interested in converting a specific set of numeric variables into factors (but not all numeric variables). I've been trying to get this to work using the lapply function and dplyr, storing my column names in a vector, however, I'm having difficulty getting it to work:
colsasfactors <- (c("Hour", "InDebt", "AppBooked"))
df <- df %>%
lapply(colnames(df) %in% colsasfactor, factor)
Clearly, I'm missing something (my suspicion being that I'm using %in% incorrectly).