Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.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
R:如何将字符串的数据帧转换为POSIXt对象?_R_Posixct - Fatal编程技术网

R:如何将字符串的数据帧转换为POSIXt对象?

R:如何将字符串的数据帧转换为POSIXt对象?,r,posixct,R,Posixct,我有一个表示时间的字符串数据帧,例如: times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"), exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")), row.names = c(NA, 3L), class = "data.frame

我有一个表示时间的字符串数据帧,例如:

times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"), 
                        exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")), 
                        row.names = c(NA, 3L), class = "data.frame")
[1] “2020-02-19 17:19:04格林威治标准时间”

太好了,现在我想把我的整个数据帧
时间
转换成这种格式

我似乎找不到顺利完成这项工作的解决办法

到目前为止,我已经尝试了一些事情:

strptime(times, '%H:%M:%S') # generates NA
strftime(times, '%H:%M:%S') # Error: do not know how to convert 'x' to class “POSIXlt”
apply(times, 2, function(x) strftime(x, '%H:%M:%S')) # Error: character string is not in a standard unambiguous format
我最接近我想要的是:

apply(times, 2, function(x) strptime(x, '%H:%M:%S'))

它生成了一个混乱的列表。我也许能找到一种使用它的方法,但肯定有一种更为直截了当的方法?

你可以使用
lappy

times[] <- lapply(times, strptime, '%H:%M:%S')
#                  exp1                exp2
# 1 2020-02-19 17:19:04 2020-02-19 17:22:04
# 2 2020-02-19 17:28:53 2020-02-19 17:31:53
# 3 2020-02-19 17:38:44 2020-02-19 17:41:45

诀窍是用
[]替换列(与用列表覆盖数据框相反),您可以使用
lappy

times[] <- lapply(times, strptime, '%H:%M:%S')
#                  exp1                exp2
# 1 2020-02-19 17:19:04 2020-02-19 17:22:04
# 2 2020-02-19 17:28:53 2020-02-19 17:31:53
# 3 2020-02-19 17:38:44 2020-02-19 17:41:45

诀窍是用
[]替换列(而不是用列表覆盖数据框)。对,我认为这与我的
应用(times,2,function(x)strtime(x,'%H:%M:%s'))的输出相同。
。我希望有一种方法可以获得与输出相同维度的数据帧?是的,只是有相同的想法,你想要一个数据帧:)请参见编辑!请注意,我添加了一些解释。对,我认为这与我的
apply(times,2,function(x)strtime(x,'%H:%M:%s'))的输出相同。
。我希望有一种方法可以获得与输出相同维度的数据帧?是的,只是有相同的想法,你想要一个数据帧:)请参见编辑!注意,我添加了一些解释。
times[] <- apply(times, 2, function(x) strptime(x, '%H:%M:%S'))