R - 如何使用同一列中每小时不同分钟的值计算

问题描述 投票:0回答:2

亲爱的Stackoverflow社区,

我有一个带有日期时间的数据集[posixct'%d。%m。%Y%H:%M']和[A]和[V]中的传感器测量值。 Datetime是一列,不同的传感器是其他列,每个传感器有一列。

我想用每个传感器列中的值计算校正值。校正值应每小时写入一个新的列。因此,我想计算如下修正:

校正= | x - (0.5 *(y + z))|

x =传感器1的值,如果分钟== '00'

y =传感器1的值,如果分钟=='03'

z =传感器1的值,如果分钟=='06'

我想要的是一个函数,它计算每小时的书面公式,但是只有在给出小时内所有三分钟('00'和'03'和'06')的值时才写出来并写出来将校正值转换为新列(Data $ correction)。我希望我能解释一下,我想做什么。

我尝试了几个循环并应用和mapply函数,但是日期格式或函数总是存在问题。这对我来说似乎是最好的方法,虽然它现在不起作用,但我希望有办法让它开始工作。我认为,写出向量并将它们合并为融合或合并可能不是最好的方法。但是现在我正在努力奋斗,现在不知道如何解决这个问题。

我真的希望你能帮助我。非常感谢。

Test_sub <- read.table(file= 'Test_sub.csv',
header=T, sep= ';', dec='.', stringsAsFactors= F)

sensor1_V_0 <- Test_sub[format(Test_sub$Datehour, format = '%M') ==           '00',]
sensor1_V_3 <- Test_sub[format(Test_sub$Datehour, format = '%M') == '03',]
sensor12_V_6 <- Test_sub[format(Test_sub$Datehour, format = '%M') == '06',]

test_sub2<- mapply(function(x, y, z) x-(0.5*(y+z)), sensor1_V_0$sensor1_V,     sensor1_V_3$sensor1_V, sensor1_V_6$sensor1_V)
r date posixct
2个回答
0
投票

让我们从创建一些假数据开始:

dill<-data.frame(time=seq(as.POSIXct("2019-01-01 11:30"), as.POSIXct("2019-01-01 13:20"), by=180),val=runif(37,0,100))

现在我们可以这样做:

require(tidyverse)
require(lubridate)
dill<- dill %>% 
group_by(hour(time)) %>% # group by the hour -- note this assumes there's only one day in the data, you'll need to adjust this if there's more than one day
filter(any(minute(time)==3) & any(minute(time)==6) & any(minute(time)==0)) %>% # remove any hours in the data that don't have minutes 0, 3 and 6
mutate(correction=abs(val[minute(time)==0]-0.5*(val[minute(time)==3]+val[minute(time)==6]))) # calculate the correction

0
投票

数据的一个例子是:

y <- seq(from= 0.1, to= 0.5, by= 0.1)
min <- as.POSIXct('2018-09-25 09:00:00')
max <- as.POSIXct('2018-09-26 17:45:00')
SEQ <- data.frame(Datehour = seq.POSIXt(min,max, by = 60*03))
str(SEQ)
SEQ <- data.frame(SEQ[format(SEQ, format = '%M') == '00' | 
                                format(SEQ, format = '%M') == '03' |
                                format(SEQ, format = '%M') == '06' |
                                format(SEQ, format = '%M') == '15' |
                            format(SEQ, format = '%M') == '30' |
                            format(SEQ, format = '%M') == '45' ,])

data <- data.frame(Datehour=SEQ, y = 0.1, z= 0.3)
© www.soinside.com 2019 - 2024. All rights reserved.