【问题标题】:Convert all columns to character except integer, posixct and Numeric将除整数、posixct 和数字之外的所有列转换为字符
【发布时间】:2020-05-18 07:46:16
【问题描述】:

我有一个包含 100 列的数据框,有没有办法将除整数、数字和 Posixct 列之外的所有列都转换为字符?

想看看这是否可行?

示例如下。出于演示目的,我在 iris 中添加了 2 个新列。谁能帮我。

str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ New1        : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... 
 $ New2        : Posixct ....... 

【问题讨论】:

    标签: r


    【解决方案1】:

    is.numeric 测试数字和整数。

    dplyr,你可以使用mutate_if

    library(dplyr)
    data <- data %>% mutate_if(~!(is.numeric(.) | is.POSIXct(.)), as.character)
    

    或者在基础 R 中使用lapply

    data[] <- lapply(data, function(x) 
                if(is.numeric(x) | is.POSIXct(.)) x else as.character(x))            
    

    【讨论】:

    • 非常感谢。但是 is.POSIXct(.) 不存在,因此会引发错误
    • @manishp 你能重启 R 再试一次吗?它不会对我抛出任何错误。例如 - iris %&gt;% mutate_if(~!(is.numeric(.) | is.POSIXct(.)), as.character)mtcars %&gt;% mutate_if(~!(is.numeric(.) | is.POSIXct(.)), as.character) 他们都没有任何 POSIXct 列。
    【解决方案2】:

    我们可以用sapply创建索引

     i1 <- !sapply(data, function(x) is.numeric(x)|is.POSIXct(x))
     data[i1] <- lapply(data[i1], as.character)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      相关资源
      最近更新 更多