You know how you can supply a vector of names to a data frame to change the col or row names of a dataframe. Is there a similar method to supply a vector of names that alters the class of each column in a dataframe? You can do this when you read in a dataframe with read.table using colClasses. What about if the dataframe is created inside R?
DF <- as.data.frame(matrix(rnorm(25), 5, 5))
str(DF) #all numeric modes
names(DF) <- c("A", "A2", "B", "B2", "Z") #I want something like this for classes
some_classes_function_like_names(DF) <- c(rep("character", 3), rep("factor", 2))
#I can do it like this but this seems inefficient
DF[, 1:3] <- lapply(DF[, 1:3], as.character)
DF[, 4:5] <- lapply(DF[, 4:5], as.factor)
str(DF)
EDIT: I changed sapply above to lapply as sapply doesn’t make sense.
EDIT 2: If there’s a way to write a user defined function that would suffice as well
It seems
class(x) <- "factor"doesn’t work and neither doesas(x, "factor"), so I don’t know of a direct way of doing what you want.…But a slightly more explicit way is:
A couple of things: you can add more cases as needed. And the first line of the function allows you to call with a single class name. The last “default” case of the
switchcalls theasfunction and you mileage might vary.