我正在嘗試在 r 中撰寫一個函式。我有一個以月份為 col 名稱的資料集。每個列由一組數字和一個名稱組成。我想選擇一個月份,然后將該列乘以十并將其存盤在一個新列中,該列用月份名稱重命名,例如 Total_(月份名稱)。謝謝
Name <- c("A" ,"B" ,"C" ," D" ,"E" ,"F")
Aug <- c("12" ,"12" ,"2" ," 5" ,"12" ,"12")
Sep <- c("15" ,"12" ,"2" ," 6" ," 5" ,"11" )
Oct <- c("8" ,"12" ,"2" ," 5" ," 5" ," 6" )
June <- c("6" ,"12" ,"2" ,"12" ,"12" ,"12")
data <- data.frame(Name,Aug,Sep,Oct,June)
my.function <- function(df,month) {
name2 <- "aug"
data <- data %>% select(1:1, contains(name2))
d <- as.data.frame(data)
d[is.na(d)] <- 0
d[d==""] <- 0
x <- paste0('sale_Total',name) # want to create a col name "Sale_Total_Month_selected"
d$(x) <- d$(name2)*10# this is not working :P
}
uj5u.com熱心網友回復:
這是你想要的?
library(tidyverse)
my.function <- function(df, month){
df |>
select(Name, !!month)|>
mutate(across(!!month, as.numeric),
"sale_Total_{month}" := !!sym(month) * 10)
}
my.function(data, "Aug")
#> Name Aug sale_Total_Aug
#> 1 A 12 120
#> 2 B 12 120
#> 3 C 2 20
#> 4 D 5 50
#> 5 E 12 120
#> 6 F 12 120
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/524519.html
標籤:r