【问题标题】:converting time in RR中的转换时间
【发布时间】:2014-01-20 07:30:15
【问题描述】:

这是我的功能:

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。谁能告诉我我做错了什么?我只是没看到。

这是我得到的错误:

$&lt;-.data.frame(*tmp*, "Timestamp", value = list(sec = c(0, : 替换有9行,数据有78

【问题讨论】:

    标签: r for-loop time


    【解决方案1】:

    由于未提供任何数据或错误消息,因此这是在黑暗中进行的尝试。

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

    x$Timestamp <- t
    

    或者更简洁:

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

    【讨论】:

    • @Justin,这是我在使用这段代码时遇到的错误:x$Timestamp $<-.data.frame(*tmp*, "Timestamp", value = list(sec = c(NA_real_, : 替换有 9 行,数据有 78 行) 中的错误
    • 请包含dput(x) 或其中的一部分dput(head(x)) 以重现您的错误,我很乐意提供帮助。否则,我无法知道您的代码为什么起作用或不起作用。
    • @贾斯汀,当我运行我的代码时,这是我收到的错误警告消息:1:在[&lt;-.factor(*tmp*, x$Timestamp == target[i], value = list (:无效因子级别,生成 2:在 x[...]
    • 这就是为什么我让你使用dput...使用read.table(..., stringsAsFactors=FALSE)
    • 以前从未听说过 dput。不管怎样,我已经按照你说的做了,现在它显示了这个错误:$&lt;-.data.frame(*tmp*, "Timestamp", value = list(sec = c(0, : replacement has 9 rows, data has 78) >
    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 2012-05-28
    • 2023-03-25
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    相关资源
    最近更新 更多