I've managed to simplify this down to the fact that you can sub assign with a symbol when using a data frame, but not with a tibble.
library(tibble)
library(rlang)
df <- data.frame(x = 1)
tbl <- tibble(x = 1)
x_sym <- sym("x")
x_chr <- "x"
df[[x_chr]] <- 2
tbl[[x_chr]] <- 2
# Can subset-assign with a symbol for data frames
df[[x_sym]] <- 2
# Can't subset-assign with a symbol for tibbles
tbl[[x_sym]] <- 2
#> Error: Can't use character names to index an unnamed vector.
I'll report this upstream.
I don't think this has anything to the version of R you are using. It is just that you started with a data frame, but group_split() returns tibbles.
To patch your function in the meantime, you can wrap ensym(.x) in as_name() to convert the symbol to a character, which you can sub assign with.
library('rlang')
library('dplyr')
library('purrr')
### this function nowcasts a time series based on an another more timely one
fill_forward <- function(df, .x, .y) {
.x <- as_name(ensym(.x))
.y <- as_name(ensym(.y))
if (!anyNA(df[[.x]])) {
df[["obs_status"]] <- "A"
df[["conf_status"]] <- "F"
df[[.y]] <- NULL
return(df)
}
firstempty <- min(which(is.na(df[[.x]])))
i <- numeric(0)
df[["obs_status"]] <- "A"
df[["conf_status"]] <- "F"
for (i in firstempty:length(df[[.x]])) {
df[[.x]][i] <- df[[.y]][i] / df[[.y]][i - 1] * df[[.x]][i - 1]
df[["obs_status"]][i] <- "E"
}
df[[.y]] <- NULL
df <- na.omit(df)
df
}
df1 <- data.frame(
time = c(1995, 1996, 1997, 1998),
value.x = c(2, 3, 4, NA),
value.y = c(3, 4, 7, 10.5)
)
df <- data.frame(
country = c("AUT", "AUT", "AUT", "AUT", "BEL", "BEL", "BEL", "BEL"),
time = c(1995, 1996, 1997, 1998, 1995, 1996, 1997, 1998),
value.x = c(2, 3, 4, NA, 5, 7, 8, NA),
value.y = c(3, 4, 7, 10.5, 5.5, 9, 12, 16)
)
### 1 country
test1 <- fill_forward(df1, value.x, value.y)
### more than 1 country
test2 <- df %>%
group_split(country) %>%
map_df(fill_forward, value.x, value.y)
Created on 2021-06-04 by the reprex package (v2.0.0)