【问题标题】:Data Type Conversion leading to NULL values in R数据类型转换导致 R 中的 NULL 值
【发布时间】:2020-04-06 08:33:59
【问题描述】:

问题: 我有一个要导入的数据框 - 372x58。我需要将特定列从“因子”数据类型转换为“字符”。然而, 1)特定列的类和摘要为NULL 2) 一旦我为特定列运行 as.character 代码,它就会显示为 NULL。

输入案例 1

AS_1.2 <- as.data.frame(AS_1.1)
> typeof(AS_1.2)
[1] "list"
> class(AS_1.2)
[1] "data.frame"
> class(AS_1.2$Open_for)
[1] "NULL"
> summary(AS_1.2$Open_for)
Length  Class   Mode 
     0   NULL   NULL 

案例 2

install.packages("lubridate")
library("lubridate")

x <- as.character(AS_1.2$Open_for)
cleaned <- gsub("([hms])", "\\U\\1", x, perl=TRUE) # upper case the h, m and s
duration(cleaned)
z <- as.numeric(duration(cleaned), units="hours")
AS_1.2$Open_for <- z

案例 1 没有错误 案例 2 的错误

> x <- as.character(AS_1.2$Open_for)
> cleaned <- gsub("([hms])", "\\U\\1", x, perl=TRUE) # upper case the h, m and s
> duration(cleaned)
[1] "Duration(0)"
> z <- as.numeric(duration(cleaned), units="hours")
> AS_1.2$Open_for <- z
Error in `$<-.data.frame`(`*tmp*`, "Open_for", value = numeric(0)) : 
  replacement has 0 rows, data has 372
> 

【问题讨论】:

  • 你使用什么函数/包来导入?主要区别之一是它们如何处理字符串(即字符串作为因子 = TRUE/FALSE)。
  • AS_1.2
  • 看起来“Open_for”不是 AS_1.1 中的列。检查您的数据框中的拼写和大小写 (colnames(AS_1.2)),希望这一切都能解决。
  • 感谢@SymbolixAU 的编辑。将研究发布的最佳做法
  • @DanielV - 这不是问题所在。我并排查找了 AS_1.1 和 1.2 文件,列名完全相同

标签: r type-conversion character


【解决方案1】:

保持大部分代码不变,使用 read.table() 而不是 read.csv2()

输出

z <- as.numeric(duration(cleaned), units="hours")

AS_1.2$Open.for <- z

str(AS_1.2$Open.for)

num [1:372] NA NA NA NA NA NA NA NA NA NA ...

summary(AS_1.2$Open.for)

最小。第一曲。中位数平均第三曲。最大限度。北美 0.00056 0.00139 0.02556 17.39000 0.31280 311.10000 35

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2011-11-12
    • 2016-02-08
    • 2016-10-22
    相关资源
    最近更新 更多