转换多列类

Dar*_*sai 5 r dataframe

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

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
Run Code Online (Sandbox Code Playgroud)

我们可以看到所有类都是整数.我想要实现的是将4个类分别转换为整数,数字,字符因子.当然,我可以使用

df$V1 <- as.XXX(df$V1)
Run Code Online (Sandbox Code Playgroud)

对于每一列,但我认为这是低效的.

预期产出

# '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
Run Code Online (Sandbox Code Playgroud)

问题2

我在R中分配 @joran的答案将数据框中的列分配(或复制)到另一个,并运行以下代码:

myclass <- c("integer", "numeric", "character", "factor")
df.2 <- df
df.2[] <- mapply(FUN = as, df.2, myclass, SIMPLIFY = F)
Run Code Online (Sandbox Code Playgroud)

当我打电话时df.2,会出现错误:

as.character.factor(x)出错:格式错误的因素

然而,这是可以调用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"
Run Code Online (Sandbox Code Playgroud)

为什么as函数不能处理类numericfactor

www*_*www 7

我们可以使用mapply并提供函数作为列表来转换列.

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
Run Code Online (Sandbox Code Playgroud)