我們的想法是,根據列名在
01/01/2021和01/08/2021之間的列名獲得總和:
# define rank parameters {start-end}
first_date <- format(Sys. Date(), "01/01/%Y")
actual_date <- format(Sys. Date() %m-% months(1)。 "01/%m/%Y")
# get the sum of the rows between first_date and actual_date
df$ytd<- rowSums(df[/span>as. character(seq(first_date,
actual_date))])
然而,當應用時,出現了下一個錯誤:
seq.default(first_date, to_date)中的錯誤。 'from'必須是一個有限的數字
。
預期的輸出是一個新的列,它取的是指定等級之間的行的總和。
data
df < -結構(list(country= c("墨西哥", "墨西哥", "墨西哥", "墨西哥"
)。 `01//2021` = c(12, 23, 13, 12), `01/02/2021` = c(12, 23,
13, 12), `01/03/2021`=c(12, 23, 13, 12), `01/04/2021`=c(12,
23, 13, 12), `01/05/2021`= c(12, 23, 13, 12), `01/06/2021`= c(12,
23, 13, 12), `01/07/2021`= c(12, 23, 13, 12), `01/08/2021`= c(12,
23, 13, 12), `01/09/2021`= c(12, 23, 13, 12), `01/10/2021`= c(12,
23, 13, 12), `01/11/2021`=c(12, 23, 13, 12), `01/12/2021`=c(12,
23, 13, 12)), row.names = c(NA, -4L), class = c("tbl_df", "tbl",
"data.frame"))
我怎樣才能正確地應用一個函式來獲得這個輸出呢?
uj5u.com熱心網友回復:
format和seq不起作用,即seq期望一個Date類,而format是一個character類。 相反,在across或select中使用范圍運算子
library(dplyr)
out <- df %>%
mutate(ytd = rowSums(across(all_of(first_date)。 all_of(actual_date)))
輸出
> out$ytd
[1] 96 184 104 96
uj5u.com熱心網友回復:
一個使用match的基礎R方法 -
df$ytd < - rowSums(df[match(first_date, names(df))。 match(actual_date, names(df))])
df$ytd
#[1] 96 184 104 96
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/310883.html
標籤:
上一篇:我試圖對一個陣列進行排序,然后將其映射到一個新的陣列中,但是排序不起作用(映射起作用)。
下一篇:獲取帶有時區的星期范圍
