通过TimeStamp对数据进行子集和绘图

时间:2017-01-10 14:34:54

标签: r

我有一个data.frame P1(5000rows x 4cols),并且当第1列中的时间戳落入由向量TimeStamp确定的设定范围时,想要在第2,3和4列中保存数据子集(很快)。

E.g。将第2,3和4列中的所有值放入新的data.frame并调用每个数据部分:Condition.1.P1,Condition.2.P1等。

我之所以要单独标注,因为我有35个版本的P1(P2,P3,P33等),需要能够将它们融合在一起绘制它们。

dput(TimeStamp)
c(18, 138, 438, 678, 798, 1278, 1578, 1878, 2178)


dput(head(P1))
structure(list(Time = c(0, 5, 100, 200, 500, 1200), SkinTemp = c(27.781, 
27.78, 27.779, 27.779, 27.778, 27.777), HeartRate = c(70, 70, 
70, 70, 70, 70), RespirationRate = c(10, 10, 10, 10, 10, 10)), .Names = c("Time", 
"SkinTemp", "HeartRate", "RespirationRate"), row.names = c(NA, 
6L), class = "data.frame")

2 个答案:

答案 0 :(得分:2)

您想要按时间戳范围分隔数据并将其放入列表中吗?这可能是你想要的:

TimeStamp <- c(18, 138, 438, 678, 798, 1278, 1578, 1878, 2178)

dat <- structure(list(Time = c(0, 5, 100, 200, 500, 1200), SkinTemp =(27.781, 
27.78, 27.779, 27.779, 27.778, 27.777), HeartRate = c(70, 70, 
70, 70, 70, 70), RespirationRate = c(10, 10, 10, 10, 10, 10)), .Names = c ("Time", 
"SkinTemp", "HeartRate", "RespirationRate"), row.names = c(NA, 
6L), class = "data.frame")

dat$Segment <- cut(dat$Time,c(-Inf,TimeStamp))
split(dat,dat$Segment)

答案 1 :(得分:1)

P2 = data.frame(NA, NA, NA, NA) # Create empty data.frame
for (i in 1:length(ts)){
    P3 = data.frame() # Create empty changing data.frame
    if (i == 1) {ts1 = 0} else {ts1 = ts[i-1]} #First time stamp starts at 0
    ts2 = ts[i]
    P3 = subset(P1, P1$Time > ts1 & P1$Time < ts2)[,c(2,3,4)] #Subset the columns and assign to P3
    if (nrow(P3) == 0){P3 = data.frame(NA, NA, NA)} #If the subset is empty, assign NA
    P3$TimeStamp = paste(ts1,ts2,sep="-") # Append TimeStamp to the P3
    colnames(P3) = colnames(P2) #Make sure column names are same to allow rbind
    P2 = rbind(P2,P3) #Append P3 to P2
}
P2 = P2[c(2:nrow(P2)),] #Remove the first row (that has NA)
colnames(P2) = c("SkinTemp", "HeartRate", "RespirationRate", "TimeStamp") #Provide column names)
rm(P3); rm(i); rm(ts1); rm(ts2) #Cleanup