r - 对 NA 值使用 strptime
问题描述
我需要使用 strptime 函数来转换如下所示的时间戳:
Tue Feb 11 12:18:36 +0000 2014
Tue Feb 11 12:23:22 +0000 2014
Tue Feb 11 12:26:26 +0000 2014
Tue Feb 11 12:28:02 +0000 2014
根据需要,我已将其复制到 csv 文件中并将其读入 R:
timestamp_data <- read.table('timestamp_data.csv')
然后我尝试使用以下方法将其转换为可识别的时间:
timestamp_data_formatted <- strptime(timestamp_data[,1], format ="%a %b %d %H:%M:%S %z %Y")
当我尝试在 R 中查看格式化数据时,我仍然得到 NA 值。我认为问题在于,当我在 R 中查看导入的 csv 数据时,它没有显示“+0000”,而是显示为 0。我该如何解决这个问题?
解决方案
你用的是read.table
,不是read.csv
。前者在空格上拆分,因此将日期时间拆分为多列:
df <- read.table(text = 'Tue Feb 11 12:18:36 +0000 2014
Tue Feb 11 12:23:22 +0000 2014
Tue Feb 11 12:26:26 +0000 2014
Tue Feb 11 12:28:02 +0000 2014')
df
#> V1 V2 V3 V4 V5 V6
#> 1 Tue Feb 11 12:18:36 0 2014
#> 2 Tue Feb 11 12:23:22 0 2014
#> 3 Tue Feb 11 12:26:26 0 2014
#> 4 Tue Feb 11 12:28:02 0 2014
str(df)
#> 'data.frame': 4 obs. of 6 variables:
#> $ V1: Factor w/ 1 level "Tue": 1 1 1 1
#> $ V2: Factor w/ 1 level "Feb": 1 1 1 1
#> $ V3: int 11 11 11 11
#> $ V4: Factor w/ 4 levels "12:18:36","12:23:22",..: 1 2 3 4
#> $ V5: int 0 0 0 0
#> $ V6: int 2014 2014 2014 2014
如果您使用read.csv
(带有合理的参数),它会起作用:
df <- read.csv(text = 'Tue Feb 11 12:18:36 +0000 2014
Tue Feb 11 12:23:22 +0000 2014
Tue Feb 11 12:26:26 +0000 2014
Tue Feb 11 12:28:02 +0000 2014', header = FALSE, stringsAsFactors = FALSE)
df$datetime <- as.POSIXct(df$V1, format = '%a %b %d %H:%M:%S %z %Y', tz = 'UTC')
df
#> V1 datetime
#> 1 Tue Feb 11 12:18:36 +0000 2014 2014-02-11 12:18:36
#> 2 Tue Feb 11 12:23:22 +0000 2014 2014-02-11 12:23:22
#> 3 Tue Feb 11 12:26:26 +0000 2014 2014-02-11 12:26:26
#> 4 Tue Feb 11 12:28:02 +0000 2014 2014-02-11 12:28:02
str(df)
#> 'data.frame': 4 obs. of 2 variables:
#> $ V1 : chr "Tue Feb 11 12:18:36 +0000 2014" "Tue Feb 11 12:23:22 +0000 2014" "Tue Feb 11 12:26:26 +0000 2014" "Tue Feb 11 12:28:02 +0000 2014"
#> $ datetime: POSIXct, format: "2014-02-11 12:18:36" "2014-02-11 12:23:22" ...
我在as.POSIXct
这里使用而不是strptime
因为前者通常是您需要的,但strptime
现在也可以使用。
推荐阅读
- python - 如何删除熊猫中多个括号之间的单词?
- java - 如何在 Visual Studio Code (v 1.27.2) 中设置 java 类路径?
- jquery - 一页中有多个表单,数据应存储在不同的表中
- python - 如何使用 imdb 中的 imdbpy 检索特定电影 ID 的情节关键字
- android - NotificationCompat.Builder() 不接受 Channel Id 作为参数
- javascript - 如何将变量从一个函数调用到另一个函数
- bash - 在 shell 中搜索字符串,如果找不到则打印新行
- javascript - how to combine objects in an array that have the same key in javascript?
- django - 如何为 CD 的每个代码分支配置一个 docker 容器
- git - git rebase -i --root:'致命:不明确的参数'':未知的修订或路径不在工作树中。