0
votes

I have a population of individuals that have attributes for whether or not they are alive, their sex, and age:

ind <- vector(mode="list", 10)
  for(i in seq(ind)){
    ind[[i]]$alive <- 1 
    ind[[i]]$sex <- sample(c("female","male"),1) 
    ind[[i]]$age <- round(runif(1, min=1, max=10))
  }
ind

Using lapply, I can increase the age of each individual, and get the list of individuals back with all of their attributes:

lapply(ind,function(x){x$age <- x$age+1; x})

Is there a map function from purrr that can do the same exact thing (give the same output as lapply)? When I use map(), I only get back a list of ages, and not all of the attributes for each individual:

map(ind, ~.$age+1)
1
It's probably not the cleanest way, but the same logic as you used in lapply works for map too - map(ind, ~{.$age <- .$age+1; .}) - thelatemail

1 Answers

1
votes

After reading the help files, it looks like ?update_list is what you want:

map(ind, update_list, age = ~age + 1)

So apply to each item of ind the update_list function, and replace the age variable with the result of the expression age + 1.