我是在R工作,并有一个与各种系列的数据。我需要对大多数这些列执行以下两个操作:
我尝试了一个列的解决方案
df %>% mutate( pmax(0,x - pmax(lag(x), lag(x,2), lag(x,3), lag(x,4))) )但是,我想可以使用dplyr的dplyr跨和purrr语法对所有列和这两个操作执行此操作。对怎么做有什么想法吗?
发布于 2022-11-09 00:58:48
您可以在dplyr包中使用across()函数。
#Define some test data
df <- data.frame( x= round(runif(100, 10, 15)), y=round(rnorm(100, 10, 5), 1))
#define the function to apply on each column
mypmax <- function(i){
pmax(0,i - pmax(lag(i), lag(i,2), lag(i,3), lag(i,4)))
}
#apply the function on columns 1 & 2.
#create new column names to store the results.
df %>% mutate(across(c(1,2), mypmax, .names = "new_{.col}" ) )
x y new_x new_y
1 12 7.3 NA NA
2 14 10.9 NA NA
3 10 17.8 NA NA
4 14 12.5 NA NA
5 15 10.0 1 0.0
6 14 11.6 0 0.0
7 10 7.9 0 0.0
8 12 8.6 0 0.0
9 11 11.3 0 0.0
10 11 4.7 0 0.0https://stackoverflow.com/questions/74368709
复制相似问题