Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将strtime应用于本地数据帧_R_String_Date_Escaping - Fatal编程技术网

将strtime应用于本地数据帧

将strtime应用于本地数据帧,r,string,date,escaping,R,String,Date,Escaping,我想我有一个与\相关的问题,我无法处理 下面是我用read\u csv阅读的data.frame的DateTime列的摘录: earthquakes[1:20,1] Source: local data frame [20 x 1] DateTime (chr) 1 1964/01/01 12:21:55.40 2 1964/01/01 14:16:27.60 3 1964/01/01 14:18:53.90 4

我想我有一个与
\
相关的问题,我无法处理

下面是我用
read\u csv
阅读的data.frame的DateTime列的摘录:

earthquakes[1:20,1]
Source: local data frame [20 x 1]
                 DateTime
                    (chr)
1  1964/01/01 12:21:55.40
2  1964/01/01 14:16:27.60
3  1964/01/01 14:18:53.90
4  1964/01/01 15:49:47.90
5  1964/01/01 17:26:43.50
我的目标是提取这里的年份。手工操作

> format(strptime(c("1964/01/01 12:21:55.40","1964/01/01 12:21:55.40","1964/01/01 14:16:27.60"), "%Y/%m/%d %H:%M:%OS"), "%Y")
[1] "1964" "1964" "1964"
按预期工作。但是,

> strptime(earthquakes[1:5,1], "%Y/%m/%d %H:%M:%OS")
DateTime 
      NA 
我的直觉是这个问题与

as.character(earthquakes[1:5,1])
[1] "c(\"1964/01/01 12:21:55.40\", \"1964/01/01 14:16:27.60\", \"1964/01/01 14:18:53.90\", \"1964/01/01 15:49:47.90\", \"1964/01/01 17:26:43.50\")"
因此,数据框中的列也包含“via the escape
\”
。但我不知道如何处理这件事

考虑到年份是前四个条目,它看起来也不错(但不那么优雅,imho)

但那就相应地给出了

[1] "c(\"1"
显然,我能做到

substr(earthquakes[1:5,1],4,7)

但这只适用于第一行。

显然您有一个
dplyr::tbl_df
,默认情况下,
[
从不将单个列简化为原子向量(与应用于基R
data.frame
相反)。因此,您可以使用
[[
$
提取列,然后将其简化为原子向量

一些例子:

data(iris)
library(dplyr)
x <- tbl_df(iris)
x[1:5, 1]
#Source: local data frame [5 x 1]
#
#  Sepal.Length
#         (dbl)
#1          5.1
#2          4.9
#3          4.7
#4          4.6
#5          5.0
iris[1:5, 1]
#[1] 5.1 4.9 4.7 4.6 5.0
x[[1]][1:5]
#[1] 5.1 4.9 4.7 4.6 5.0
x$Sepal.Length[1:5]
#[1] 5.1 4.9 4.7 4.6 5.0
数据(iris)
图书馆(dplyr)

x令人惊讶的是,即使我没有发布MWE,你也发现了这个问题!这解释了为什么它在某个时候起作用,但在之后就不再起作用了-我只需要
dplyr
在这个过程的后期(我太不好意思发布了,代码有时似乎不太可能起作用,然后就不再起作用了).@您可以保持数据原样,只需将
strtime(地震[1:5,1],%Y/%m/%d%H:%m:%OS”)
替换为
strtime(地震[[1]][1:5],%Y/%m/%d%H:%m:%OS”)
data(iris)
library(dplyr)
x <- tbl_df(iris)
x[1:5, 1]
#Source: local data frame [5 x 1]
#
#  Sepal.Length
#         (dbl)
#1          5.1
#2          4.9
#3          4.7
#4          4.6
#5          5.0
iris[1:5, 1]
#[1] 5.1 4.9 4.7 4.6 5.0
x[[1]][1:5]
#[1] 5.1 4.9 4.7 4.6 5.0
x$Sepal.Length[1:5]
#[1] 5.1 4.9 4.7 4.6 5.0