gpt4 book ai didi

r - 转换多个列类

转载 作者:行者123 更新时间:2023-12-02 03:03:39 24 4
gpt4 key购买 nike

我认为这是一个简单的问题,但我还没有找到合适的解决方案。首先从一组简化的数据开始:

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 个类分别转换为整数、数字、字符因子。当然,我可以使用

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时,出现错误:

Error in as.character.factor(x) : malformed factor

但是,调用str(df.2)是可以的,显然只有V1V3达到了我的请求。

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函数不能处理类numericfactor

最佳答案

我们可以使用maply并以列表形式提供函数来转换列。

df <- as.data.frame(matrix(1:20, 5, 4))

df[] <- mapply(function(x, FUN) FUN(x),
df,
list(as.integer, as.numeric, as.character, as.factor),
SIMPLIFY = FALSE)
str(df)
# '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

关于r - 转换多个列类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242083/

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