Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign different classes within a for loop

Tags:

for-loop

class

r

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
like image 875
Joachim Schork Avatar asked Aug 16 '26 08:08

Joachim Schork


1 Answers

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"
like image 160
zx8754 Avatar answered Aug 19 '26 00:08

zx8754