在 dplyr 的 mutate 中使用使用 for 循环的函数是个好主意

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

所以我有一个函数,它的想法是对数字向量进行操作。例如。温度向量。我想计算热浪(以非常简单的方式......)。假设连续三天气温高于 30°C,热浪就开始了。

所以我需要一个反向引用来存储当前热浪已经持续了多长时间。我编写了一个内部使用 for 循环的函数。在伪代码中,它看起来像这样:

is_heatwave = function(vals){
  
  length_heatwave = 0
  
  # returns a vector with the length of the input vals
  day_in_heatwave = vector(length=length(vals))
  days_in_current_heatwave =c()
  
  for(i in 1:length(vals)){
    val = vals[[i]]
    
    if(val > 30){
      length_heatwave = length_heatwave + 1
      days_in_current_heatwave = c(days_in_current_heatwave, i)
    }else{
      length_heatwave = 0
    }
    
    ... some more code
  }
  
  return(day_in_heatwave)
    
}

这段代码可能是错误的。但其想法是,该函数将长度与 data.frame 的行数相同的向量作为输入。并返回相同长度的向量。

我的想法是有一个可以像这样使用的功能:

df = data.frame(
  temps = c(30,30,32,30,24)
)

df %>% mutate(is_heatwave = is_heatwave(temps))

我只是想问这通常是一个好主意还是有更好的主意?

r dplyr mutate
1个回答
0
投票

你可以试试

set.seed;df = data.frame(
  temps = sample(25:40, 100,replace = T)
)
df %>% 
  mutate(heatwave_length = cumsum(temps>=30)-cummax((temps<30)*cumsum(temps>=30)))%>% 
   as_tibble()
# A tibble: 100 × 2
   temps heatwave_length
   <int>           <int>
 1    33               1
 2    38               2
 3    30               3
 4    35               4
 5    30               5
 6    37               6
 7    35               7
 8    35               8
 9    38               9
10    29               0
© www.soinside.com 2019 - 2024. All rights reserved.