Hello,
Please could you help with (what I thought was going to be) a simple map function? I wish to assign values by mapping through a list. I can do this OK for a single value using the purrr::assign_in() function, as shown in the reprex. I wish to assign a vector of values (for example a sequence of c(99, 100, 101) in place of existing values, but I cannot work it out.
I spent hours on this last night without a breakthrough, so any advice would be welcome.
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
oranges <- list(
tibble(
admit_date = seq.Date(from = as_date("2020-02-01"), by = "day", length.out = 12),
vals = seq(1:12)
),
tibble(
admit_date = seq.Date(from = as_date("2020-02-08"), by = "day", length.out = 12),
vals = seq(13, 24)
))
# To assign a single value (99)
map(oranges, ~assign_in(.x, c(2,1), 99))
#> [[1]]
#> # A tibble: 12 x 2
#> admit_date vals
#> <date> <dbl>
#> 1 2020-02-01 99
#> 2 2020-02-02 2
#> 3 2020-02-03 3
#> 4 2020-02-04 4
#> 5 2020-02-05 5
#> 6 2020-02-06 6
#> 7 2020-02-07 7
#> 8 2020-02-08 8
#> 9 2020-02-09 9
#> 10 2020-02-10 10
#> 11 2020-02-11 11
#> 12 2020-02-12 12
#>
#> [[2]]
#> # A tibble: 12 x 2
#> admit_date vals
#> <date> <dbl>
#> 1 2020-02-08 99
#> 2 2020-02-09 14
#> 3 2020-02-10 15
#> 4 2020-02-11 16
#> 5 2020-02-12 17
#> 6 2020-02-13 18
#> 7 2020-02-14 19
#> 8 2020-02-15 20
#> 9 2020-02-16 21
#> 10 2020-02-17 22
#> 11 2020-02-18 23
#> 12 2020-02-19 24
# Attempt to map several values with assignment operator
map(oranges, ~.x[10:12,2] <- c(99, 100, 101))
#> Error in ~.x[10:12, 2] <- c(99, 100, 101): object '.x' not found
Created on 2023-02-26 by the reprex package (v0.3.0)
p.s. I'm on purrr version 0.3.4 as I've not been able to compile version 1.0.1.