在R中转换时间

时间:2014-01-02 19:03:36

标签: r for-loop time

这是我的功能:

x<-read.table(....., stringsAsFactors=FALSE, header=T);
x;

   Timestamp  time Barcode
1  11/1/2013  8:25   M01.A
2  11/1/2013  8:25   M01.B
3  11/1/2013  8:43   M02.A
4  11/1/2013  8:43   M02.B
5  11/1/2013  9:03   M03.A
6  11/1/2013  9:03   M03.B
7  11/1/2013  9:18   M04.A
8  11/1/2013  9:18   M04.B

dput(head(x));

structure(list(Timestamp = c("11/1/2013", "11/1/2013", "11/1/2013", 
"11/1/2013", "11/1/2013", "11/1/2013"), time = c("8:25", "8:25", 
"8:43", "8:43", "9:03", "9:03"), Barcode = c("M01.A", "M01.B", 
"M02.A", "M02.B", "M03.A", "M03.B")), .Names = c("Timestamp", 
"time", "Barcode"), row.names = c(NA, 6L), class = "data.frame")

target<- x$Timestamp;
t<- strptime(x$Timestamp, format = "%m/%d/%Y");
t;
[1] "2013-11-01" "2013-11-01" "2013-11-01" "2013-11-01" "2013-11-01" "2013-11-01" "2013-11-01" "2013-11-01"
for (i in seq_along(target)){
x$Timestamp[x$Timestamp == target[i]]<- t[i]
};

我正在尝试使用strptime转换日期,并且它可以工作,现在我正在尝试使用这个索引向量并替换此列x $ Timestamp。谁能告诉我我做错了什么?我只是没有看到它。

这是我得到的错误:

$<-.data.frame中的错误(*tmp*,“时间戳”,值=列表(秒= c(0,:   替换有9行,数据有78个

1 个答案:

答案 0 :(得分:0)

这是在黑暗中刺伤,因为没有提供数据或错误消息。

但是,t的长度与x$Timestamp相同,因此您无需进行这些体操。相反,您可以直接替换:

x$Timestamp <- t

或者更简洁:

x$Timestamp <- strptime(x$Timestamp, format='%m/%d/%Y')