I want to program a for loop, in which I need to convert the classes of some columns of a data.frame to character first. After some operations (which are irrelevant for this problem) I need to convert the columns back to their original classes.
The conversions of the columns to their original classes have to be done within the for loop. How could I do that?
Here is some data and an exemplary for loop:
# Example data
data <- data.frame(x1 = as.numeric(1:5), x2 = as.factor(7:3))
for(i in 1:ncol(data)) {
# Save original class.
class_col_i <- class(data[ , i])
# Convert column as character.
data[ , i] <- as.character(data[ , i])
# (Here I will do some operations, which are irrelevant for this problem.)
# Here I need to convert the column back to its original class.
# How can I do that?
# data[ , i] <- class_col_i... ???
}
class(data$x1) # This should be a numeric
class(data$x2) # This should be a factor
Using match.fun, see this example:
#dummy data
d <- mtcars
class(d$gear)
# [1] "numeric"
#change to character
classOrg <- class(d$gear)
d$gear <- as.character(d$gear)
class(d$gear)
# [1] "character"
#do some fun stuff
# ... d$gear
#convert it back
myConvertFun <- match.fun(paste0("as.", classOrg))
d$gear <- myConvertFun(d$gear)
class(d$gear)
# [1] "numeric"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With