在R中每t个时间单位保存数据

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

我想循环移动并以特定的时间间隔保存一个值。我正在考虑这种形式的东西:

    t <- 0
    t_end <- 10
    time_step <- 0.01
    record_interval <- 1
    while (t <= t_end){
        if (t %% record_interval == 0) print(t)
        t <- t + time_step
    }

但是,由于机器精度问题,这样做当然会失败。

我能做到:

if (isTRUE(all.equal(t %% record_interval,0, tolerance = time_step*0.1))) { ...

但即使这样也会失败,因为有时它给出的是 record_interval 的模而不是 0。

因此,我可以使用 or 语句运行我的代码,使用上面的内容并检查模数是否等于 record_interval,但这非常难看。我确信有一个明显、简单的方法可以解决这个问题,但我不知所措。我不想引入不必要的整数计数器(all.equal 部分可以工作,只是不太漂亮,所以看起来没那么糟糕),并且我希望能够根据需要更改 time_step 和 record_interval 。

r modulo
1个回答
0
投票

一种选择是使用

tidyverse
创建一个名为您的百分位值的新列,将数据过滤到您想要的间隔,然后删除新列。

# Load tidyverse
library(tidyverse)

# Create example data
dat <- data.frame(
  t = seq(0,10,0.01)
)

head(dat)
#>      t
#> 1 0.00
#> 2 0.01
#> 3 0.02
#> 4 0.03
#> 5 0.04
#> 6 0.05

# Create new column, filter the time interval you want, then remove the new column
dat2 <- dat %>%
  mutate(hundredths = floor(t * 100) %% 10) %>%
  filter(hundredths == 7) %>%
  select(-hundredths)

head(dat2)
#>      t
#> 1 0.07
#> 2 0.17
#> 3 0.27
#> 4 0.37
#> 5 0.47
#> 6 0.57

创建于 2023-12-01,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.