【发布时间】:2018-11-10 18:24:28
【问题描述】:
我认为这是一个简单的问题,但我还没有找到合适的解决方案。从一组简化数据开始:
df <- as.data.frame(matrix(1:20, 5, 4))
str(df)
# 'data.frame': 5 obs. of 4 variables:
# $ V1: int 1 2 3 4 5
# $ V2: int 6 7 8 9 10
# $ V3: int 11 12 13 14 15
# $ V4: int 16 17 18 19 20
我们可以看到所有的类都是整数。我想要实现的是将 4 个类分别转换为 integer、numeric、character、 和 factor。当然,我可以使用
df$V1 <- as.XXX(df$V1)
对于每一列,但我认为它是低效的。
预期输出
# 'data.frame': 5 obs. of 4 variables:
# $ V1: int 1 2 3 4 5
# $ V2: num 6 7 8 9 10
# $ V3: chr "11" "12" "13" "14" ...
# $ V4: Factor w/ 5 levels "16","17","18",..: 1 2 3 4 5
问题 2
我在R Assign (or copy) column classes from a data frame to another 中引用@joran 的答案并运行以下代码:
myclass <- c("integer", "numeric", "character", "factor")
df.2 <- df
df.2[] <- mapply(FUN = as, df.2, myclass, SIMPLIFY = F)
当我拨打df.2时,出现错误:
as.character.factor(x) 中的错误:因子格式错误
但是,可以拨打str(df.2),显然只有V1 和V3 能满足我的要求。
str(df.2)
# 'data.frame': 5 obs. of 4 variables:
# $ V1: int 1 2 3 4 5
# $ V2: int 6 7 8 9 10
# $ V3: chr "11" "12" "13" "14" ...
# $ V4:Formal class 'factor' [package "methods"] with 3 slots
# .. ..@ .Data : int 16 17 18 19 20
# .. ..@ levels : chr
# .. ..@ .S3Class: chr "factor"
为什么as 函数不能处理numeric 和factor 类?
【问题讨论】: