我想编写一个for循环,我需要先将data.frame的某些列的类转换为字符。在一些操作(与此问题无关)之后,我需要将列转换回原始类。
列的转换必须在for循环中完成。我怎么能这样做?
以下是一些数据和示例for循环:
# 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
答案 0 :(得分:3)
使用match.fun
,请参阅此示例:
#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"
答案 1 :(得分:0)
试试这个:
data <- data.frame(x1 = as.numeric(1:5), x2 = as.factor(7:3))
class_col<-NULL
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?
class(data[ , i]) <- class_col[i]
}
class(data$x1) # This should be a numeric
class(data$x2)