如何在R中使用mutate而不是for循环

如何在R中使用mutate而不是for循环,r,mutate,R,Mutate,有了这个代码,我得到了向量tr,如果我可以在df3上使用mutate,并使用函数calcTr来mutate,它应该是df3的一个新列 需要注意的是,新列的最后4行没有计算(NA)。我怀疑我应该使用mutate_at,但我不知道怎么做 我的成绩(tr)很好。包litteR仅用于计算trimean(q1+2*q2+q3)/4 library(tidyverse) library(litteR) # to compute trimean #> #> litteR version: 0.8

有了这个代码,我得到了向量
tr
,如果我可以在
df3
上使用
mutate
,并使用函数
calcTr
mutate
,它应该是
df3
的一个新列

需要注意的是,新列的最后4行没有计算(
NA
)。我怀疑我应该使用
mutate_at
,但我不知道怎么做

我的成绩(
tr
)很好。包
litteR
仅用于计算trimean
(q1+2*q2+q3)/4

library(tidyverse)
library(litteR) # to compute trimean
#> 
#> litteR version: 0.8.2
#> Type create_litter_project() to create a new project.
#> Type vignette("litteR-manual") to open the user manual.
#> Open the data file and check the presence of the column headers 'spatial_scale' and 'date'.
#> Open the settings file and check the settings.
#> Type litter() to start litteR.
set.seed(1234)

df <- tibble(date = rep(1:20, 3),
             country = c(rep('x', 20), rep('y', 20), rep('z', 20)),
             a = runif(60),
             b = runif(60),
             c = runif(60))

calcTr <- function(df, t1, gap){
  df2 <- df %>% filter(row(.) >= t1, row(.) < (t1 + gap))
  trimean(as.vector(t(df2)), na.rm = FALSE)
}

cs <- c('x', 'y')

df2 <- df %>%
  filter(country %in% cs) %>%
  select(date, country, a) %>%
  group_by(country) %>% 
  pivot_wider(names_from = country, values_from = a) %>%
  ungroup() %>% select(-date)

gap <- 5
k <- nrow(df2) - (gap - 1)
tr <- NULL
for (t in 1:k) {
  tr <- c(tr, calcTr(df2, t, gap))
}

tr
#>  [1] 0.3530834 0.5268562 0.4862586 0.5348352 0.6095975 0.5608634 0.5037747
#>  [8] 0.5147133 0.4735918 0.4472276 0.3953627 0.4507762 0.3942934 0.3839828
#> [15] 0.3528786 0.3968370
Created on 2021-05-18 by the reprex package (v2.0.0)
库(tidyverse)
图书馆(垃圾)#计算trimean
#> 
#>垃圾版本:0.8.2
#>键入create\u\u project()以创建新项目。
#>键入vignette(“垃圾手册”)打开用户手册。
#>打开数据文件并检查列标题“spatial_scale”和“date”是否存在。
#>打开设置文件并检查设置。
#>键入little()以启动little。
种子集(1234)
df%
按(国家)划分的组别%>%
透视图(名称来自=国家,值来自=a)%>%
解组()%>%select(-date)

gap我们可以使用
map

purrr::map_dbl(seq_len(k), ~ calcTr(df2, .x, gap))

我们可以使用
map

purrr::map_dbl(seq_len(k), ~ calcTr(df2, .x, gap))

能否修复您的
reprex
以包含
library(tidyverse)
以避免出现错误?谢谢。完成了。您能否修复您的
reprex
以包含
库(tidyverse)
,从而避免出现错误?谢谢。完成了,这太令人吃惊了。但是我如何使用它来变异
df2
?@sbac基于您创建的函数,它每次都使用过滤后的整个数据集。所以,一个循环会更好,所以我必须使用业余资源:
df2这太令人吃惊了。但是我如何使用它来变异
df2
?@sbac基于您创建的函数,它每次都使用过滤后的整个数据集。因此,循环会更好,因此我必须使用业余资源:
df2