【问题标题】:Convert Multiple Column Classes转换多列类
【发布时间】: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),显然只有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 类?

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    我们可以使用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
    

    【讨论】:

    • 太棒了!太感谢了!你介意解释一下为什么函数as 不能在数值和因子上工作吗?
    • @DarrenTsai 我不熟悉这种方式使用as函数。我希望其他人可以提供帮助。
    【解决方案2】:

    如果你不排除for循环方法,试试这个:

    df <- as.data.frame(matrix(1:20, 5, 4))
    type <- c("integer", "numeric", "character", "factor")
    for(i in 1:ncol(df)){
      call <- paste("as", type[i], sep = ".")
      df[[i]] <- do.call(call, list(df[[i]]))
    }
    
    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
    

    【讨论】:

      猜你喜欢
      • 2020-03-08
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多