【问题标题】:Fixin .csv file in R to avoid "character string is not in a standard unambiguous format"在 R 中修复 .csv 文件以避免“字符串不是标准的明确格式”
【发布时间】:2014-05-05 12:27:22
【问题描述】:

我正在尝试从 csv 文件中的日期变量中识别周数。 大多数列值都有正确分配的日期,例如“2006-03-23 11:11:22” 由 R 正确解释:

> strftime(as.POSIXlt("2006-03-23 11:11:22"), format="%W")
[1] "12" 

但是,某些值被分配了 0 值 - 即“0000-00-00 00:00:00”,这些值被错误地解释。

> strftime(as.POSIXlt("0000-00-00 00:00:00"), format="%W")
Error in as.POSIXlt.character("0000-00-00 00:00:00") : 
  character string is not in a standard unambiguous format

我可以用我的 csv 文件做什么来修复它?文件很大,我需要高效

【问题讨论】:

  • 你想用 0000-00-00 00:00:00 日期做什么?被排除在外了吗?设置为 0?

标签: r date csv


【解决方案1】:

你可以试试tryCatch。例如

df <- data.frame(Date = c(rep("2006-03-23 11:11:22", 3), rep("0000-00-00 00:00:00", 3)))
df$Week <- apply(df, 1, function(x) tryCatch(strftime(as.POSIXlt(x), format="%W"), error = function(e) ""))
df

                 Date Week
1 2006-03-23 11:11:22   12
2 2006-03-23 11:11:22   12
3 2006-03-23 11:11:22   12
4 0000-00-00 00:00:00     
5 0000-00-00 00:00:00     
6 0000-00-00 00:00:00   

对于非常大的数据集,您可以使用 parApply 使用所有内核来加速它
两核示例:

library(parallel)
cl <- makeCluster(getOption("cl.cores", 2))
df$Week <- parApply(cl, df, 1, function(x) tryCatch(strftime(as.POSIXlt(x), format="%W"), error = function(e) ""))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2016-12-02
    • 2021-12-30
    • 2021-05-23
    • 2018-10-07
    • 2013-08-29
    • 2015-01-27
    相关资源
    最近更新 更多