将时间戳添加到R中具有不同行号的数据帧

时间:2018-06-04 04:33:18

标签: r

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。

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

1 个答案:

答案 0 :(得分:0)

谢谢@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
}