Reputation: 1162
I have a data frame where the last column ("data") consists of a list of data frames, each of which has a "Year" and a "Yield" column. I want to add a 3rd column, "Det_Yield" to each data frame in the column. I'm wondering how to do this the "tidyverse" way.
I've done it using a loop, like this, but I would like to know how to use map or some other tidy method to do this. Thank you.
for (cty in 1:66){
corn_by_county[[3]][[cty]]$Det_Yield <- NA
yield_model <- lm(corn_by_county[[3]][[cty]]$Yield ~ corn_by_county[[3]][[cty]]$Year)
corn_by_county[[3]][[cty]]$Det_Yield <- resid(yield_model)}
Upvotes: 0
Views: 99
Reputation: 1972
You can use map
in the following way.
library(dplyr)
library(purrr)
viewOutput <- df %>%
mutate(data = map(data, ~ mutate(.x, det_yield = 'whatever')))
viewOutput$data
# [[1]]
# A tibble: 2 x 3
# year yield det_yield
# <dbl> <dbl> <chr>
# 1 1999 5 whatever
# 2 2000 6 whatever
# [[2]]
# A tibble: 2 x 3
# year yield det_yield
# <dbl> <dbl> <chr>
# 1 2001 7 whatever
# 2 2002 8 whatever
Arbitrary demo data
df <- structure(list(data = list(structure(list(year = c(1999, 2000
), yield = c(5, 6)), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame")), structure(list(year = c(2001, 2002), yield = c(7,
8)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
))
Upvotes: 1