【问题标题】:Adding timestamp to data frames with different row number in R在R中为具有不同行号的数据帧添加时间戳
【发布时间】:2018-06-04 16:29:56
【问题描述】:
x1 <- read.csv(header=TRUE, stringsAsFactors=FALSE, text='
X1,X2,X3
10,30,07:00
11,31,07:01
12,32,07:02
13,33,07:03
15,35,07:05
16,36,07:06
18,38,07:08
19,39,07:09')

write.csv(x1, file="20120204.csv", row.names=FALSE)
x2 <- read.csv(header=TRUE, stringsAsFactors=FALSE, text='
X1,X2
20,40
22,42
23,43
24,44
25,45
26,46')
write.csv(x1, file="20120205.csv", row.names=FALSE)

我正在尝试合并这两个数据框。但首先我需要在数据帧 2 中添加一个时间戳 X3 才能拥有:

X1,X2, X3
20,40, 07:00
22,42, 07:01
23,43, 07:02
24,44, 07:03
25,45, 07:04
26,46, 07:05

以便稍后我可以通过 X3 将两个文件合并在一起

final <- merge(X1, X2, by="X2", all=TRUE)

我试过写这个:

fnames <- list.files(pattern=".*\\.csv", full.names=TRUE)
first <- TRUE
times <- c("00:00", "23:59")
for (i in fnames) {
    x<-read.csv(i, header=TRUE)
    thisdate <- gsub(".*(20[0-9]{6}).csv", "\\1", i)
    twotimes <- as.POSIXct(paste(thisdate, c("00:00", "23:59")), format = "%Y%m%d %H:%M")
    x$X3 <- seq(twotimes[1], twotimes[2], by="min")
    outputfile<-paste0(tools::file_path_sans_ext(i),".csv")
    write.csv(x, file=outputfile)
    first <- FALSE
}

但是我收到这个错误,说时间戳有 1440 行,但数据 x1 和 x2 分别只有 8 和 6。

如何“强制”将时间戳添加到数据框中?

【问题讨论】:

  • MT32,您刚刚回滚了我所做的编辑(缩进、间距)以使其更清晰。
  • @smci 我怀疑你们俩同时在编辑。
  • 第一个数据框中有 8 次,但第二个数据框中只有 6 行。你真的只想从第一个数据帧中取出前 6 次并将它们添加到第二个数据帧中吗?
  • 对于你现在的做法,数据框中的行数应该等于你分配给它的时间戳的长度
  • 如果您不关心时间戳的实际值是什么,您可以索引您的序列 x$X3 &lt;- seq(twotimes[1], twotimes[2], by="min")[1:nrow(x)] 以适应数据框的大小

标签: r


【解决方案1】:

感谢@Esther 的回答!

只需添加 1:nrow 以适应数据框的大小

fnames <- list.files(pattern=".*\\.csv", full.names=TRUE)
first <- TRUE
times <- c("00:00", "23:59")
for (i in fnames) {
  x<-read.csv(i, header=TRUE)
thisdate <- gsub(".*(20[0-9]{6}).csv", "\\1", i)
twotimes <- as.POSIXct(paste(thisdate, c("00:00", "23:59")), format = "%Y%m%d %H:%M")
x$X3 <- seq(twotimes[1], twotimes[2], by="min")[1:nrow(x)]
outputfile<-paste0(tools::file_path_sans_ext(i),".csv")
write.csv(x, file=outputfile)
first <- FALSE
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-27
    • 2021-01-09
    • 2021-11-20
    • 1970-01-01
    • 2021-08-13
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多