-3

Situation: I have a nested list in the image below. I want to use purrr to iterate over the second element of each nested list and apply a date conversion function.

nested list

Problem: I can write a for loop easily to iterate over it but I want to use this with purrr. My nested list attempts have not worked out. Normal list fine, nested by position, not fine.

Reproducible example code from Maurits Evers (Thank you!)

lst <- list(
    list("one", "12345", "2019-01-01"),
    list("two", "67890", "2019-01-02"))

Any assistance appreciated!

AngryWhopper
  • 393
  • 3
  • 4
  • 16
  • 1
    Please use a reproducible example - https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example . Images are unhelpful as anyone wanting to answer your query has to type out a structure to test code. – thelatemail May 13 '19 at 23:34

1 Answers1

5

Please see the comment above to understand how to provide a reproducible example including sample data.

Since you don't provide sample data, let's create some minimal mock data similar to what is shown in your screenshot.

lst <- list(
    list("one", "12345", "2019-01-01"),
    list("two", "67890", "2019-01-02"))

To cast the third element of every list element as.Date we can then do

lst <- map(lst, ~{.x[[3]] <- as.Date(.x[[3]]); .x})

We can confirm that the third element of every list element is an object of type Date

str(lst)
#List of 2
# $ :List of 3
#  ..$ : chr "one"
#  ..$ : chr "12345"
#  ..$ : Date[1:1], format: "2019-01-01"
# $ :List of 3
#  ..$ : chr "two"
#  ..$ : chr "67890"
#  ..$ : Date[1:1], format: "2019-01-02"

Update

A more purrr/tidyverse-canonical approach would be to use modify_at (thanks @H1)

lst <- map(lst, ~modify_at(.x, 3, as.Date))

The result is the same as before.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68