我撰寫了一個函式來計算一年內每月資料的平均值(從上一個 12 月開始到現在的 9 月)。我通過此函式提供的每個資料幀(還有很多)目前都以我感興趣的變數命名。但我希望輸出使用資料幀的名稱作為變數。
例子:
year <- c(2000:2020)
`1` <- runif(21, 0,10)
`2` <- runif(21, 0,10)
`3` <- runif(21, 0,10)
`4` <- runif(21, 0,10)
`5` <- runif(21, 0,10)
`6` <- runif(21, 0,10)
`7` <- runif(21, 0,10)
`8` <- runif(21, 0,10)
`9` <- runif(21, 0,10)
`10` <- runif(21, 0,10)
`11` <- runif(21, 0,10)
`12` <- runif(21, 0,10)
dogs <- as.data.frame(cbind(year, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`))
fun_annual <- function(df) {
name = deparse(substitute(df)) #I know I can use this to get the name of the dataframe
df %>%
mutate(lag12 = lag(`12`)) %>%
rowwise() %>% # complete next calculations row by row
mutate(name = mean(c_across(c(`1`:`9`, lag12)))) %>% #mean from prev Dec to Sep
select(year, name) #by this point 'name' should be 'dogs' (name of original dataframe
}
# Final function should return a dataframe with 2 variables: year and dogs
如果有人還可以幫助弄清楚如何將月份放入函式中,則獎勵積分,因此我不必每次都更改函式中的月份!特別是如果我使用比前一年更多的月份(12 月以后)
uj5u.com熱心網友回復:
基于Pass a string as variable name in dplyr::mutate,您可以使用rlang's !!、sym()和:=.
sym取值name并將其轉換為符號。!!確保sym在 R 評估代碼之前生效。并且,由于沒有sym()<-函式,我們不能=用來修改左側,需要使用glue包語法 with :=。
此外,您可以使用dplyr::all_of獲取月份的列。
fun_annual <- function(df, months) {
name = deparse(substitute(df))
df %>%
mutate(lag12 = lag(`12`)) %>%
rowwise() %>%
mutate(!!sym(name) := mean(c_across(c(all_of(months), lag12)))) %>%
select(year, !!sym(name))
}
> fun_annual(dogs, paste(1:9))
# A tibble: 21 × 2
# Rowwise:
year dogs
<dbl> <dbl>
1 2000 NA
2 2001 4.33
3 2002 5.67
4 2003 3.68
5 2004 4.07
6 2005 5.52
7 2006 5.98
8 2007 6.34
9 2008 6.18
10 2009 3.66
# … with 11 more rows
uj5u.com熱心網友回復:
類似,但略有不同:
library(tidyverse)
fun_annual <- function(df) {
name <- quo_name(enquo(df))
df |>
mutate(lag12 = lag(`12`)) |>
rowwise() |>
mutate("{name}" := mean(c_across(c(`1`:`9`, lag12)))) |>
select(year, !!name)
}
fun_annual(dogs)
#> # A tibble: 21 x 2
#> # Rowwise:
#> year dogs
#> <dbl> <dbl>
#> 1 2000 NA
#> 2 2001 5.58
#> 3 2002 5.72
#> 4 2003 3.89
#> 5 2004 4.77
#> 6 2005 3.98
#> 7 2006 5.98
#> 8 2007 4.61
#> 9 2008 5.23
#> 10 2009 5.91
#> # ... with 11 more rows
編輯
幾個月的獎金:
fun_annual <- function(df, months) {
name <- quo_name(enquo(df))
df |>
mutate(lag12 = lag(`12`)) |>
rowwise() |>
mutate("{name}" := mean(c_across(c({{months}}, lag12)))) |>
select(year, !!name)
}
fun_annual(dogs, months = c(`1`, `2`))
#> # A tibble: 21 x 2
#> # Rowwise:
#> year dogs
#> <dbl> <dbl>
#> 1 2000 NA
#> 2 2001 4.76
#> 3 2002 4.74
#> 4 2003 5.35
#> 5 2004 8.11
#> 6 2005 2.26
#> 7 2006 1.90
#> 8 2007 5.75
#> 9 2008 8.35
#> 10 2009 4.81
#> # ... with 11 more rows
fun_annual(dogs, months = c(`1`, `4`, `5`))
#> # A tibble: 21 x 2
#> # Rowwise:
#> year dogs
#> <dbl> <dbl>
#> 1 2000 NA
#> 2 2001 3.76
#> 3 2002 5.92
#> 4 2003 3.66
#> 5 2004 5.78
#> 6 2005 4.67
#> 7 2006 3.53
#> 8 2007 5.31
#> 9 2008 7.15
#> 10 2009 5.02
#> # ... with 11 more rows
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525234.html
標籤:r功能
