gpt4 book ai didi

r - 在 for 循环中分配不同的类

转载 作者:行者123 更新时间:2023-12-01 13:43:35 25 4
gpt4 key购买 nike

我想编写一个 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

最佳答案

使用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"

关于r - 在 for 循环中分配不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37729344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com