只是一個一般性問題,我在 R 中有 3 列,只有兩個 num 列和 1 個日期列很重要。我想使用 mutate 僅替換 2018-08-11 到 2019-09-16 內的 sum_prec 中的 0 與 est_precp 數字,這在 R 中是否可能使用 mutate 或其他代碼或包。
$ sum_prec : num [1:29679] 0 0 0 0 0 0 0 0 0 0 ...
$ date : Date[1:29679], format: "2014-09-11" "2014-09-11" ...
$ est_precp : num [1:29679] 0 0 0 0 0 0 0 0 0 0 ...
uj5u.com熱心網友回復:
data.table 方式:
# assuming your data.frame is called 'df'
library(data.table)
setDT(df)
# find relevant rows and change the sum_prec to est_precp
df[ date > as.Date("2018-08-11") &
date < as.Date("2019-09-16") &
sum_prec == 0,
sum_prec := est_precp]
uj5u.com熱心網友回復:
我認為這就是您想要的,但正如 DanY 所說,如果您提供 MCVE,它會更容易。
library(magrittr)
# Example dataset
example_data <- tibble::tribble(
~sum_prec, ~date, ~est_precp,
0, "2014-09-11", 1,
0, "2018-08-11", 2
)
# Range of dates you want
dates_of_interest <- seq(as.Date("2018-08-11"), as.Date("2019-09-16"), by = "day")
# Replace values in `sum_prec` column with values from `est_precp` if
# `sum_prec` is zero and if `date` is within range
new_data <- example_data %>%
dplyr::mutate(
sum_prec = dplyr::if_else(
condition = sum_prec == 0 & as.Date(date) %in% dates_of_interest,
true = est_precp,
false = sum_prec
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328715.html
標籤:r
下一篇:在R中提取歌曲中的匹配項
