Reputation: 1384
I am trying to determine how I can add a column which is a vector to a column which is a list within the same data frame
library(tidyverse)
df <- data_frame(
dens = rnorm(1000),
id = sample(1:10, 1000, replace = TRUE),
size = sample(1:3, 1000, replace = TRUE)
) %>%
group_by(id, size) %>%
nest %>%
mutate(
dens_est = map(data, ~ KernSmooth::bkde(.$dens) %>%
bind_rows)
)
Using the results from the above, I would like to add a column to the dens_est
data frames with the associated value of the size
column.
Upvotes: 0
Views: 55
Reputation: 39154
We can use map2
to loop through the dens_est
and size
column and use mutate
to create the size
column for each data frame.
set.seed(1234)
library(tidyverse)
df <- data_frame(
dens = rnorm(1000),
id = sample(1:10, 1000, replace = TRUE),
size = sample(1:3, 1000, replace = TRUE)
) %>%
group_by(id, size) %>%
nest %>%
mutate(
dens_est = map(data, ~ KernSmooth::bkde(.$dens) %>%
bind_rows)
) %>%
mutate(
dens_est = map2(dens_est, size, ~.x %>% mutate(Size = .y))
)
df$dens_est[[1]]
# # A tibble: 401 x 3
# x y Size
# <dbl> <dbl> <int>
# 1 -4.38 0.00000568 3
# 2 -4.35 0.0000118 3
# 3 -4.33 0.0000159 3
# 4 -4.30 0.0000185 3
# 5 -4.27 0.0000213 3
# 6 -4.25 0.0000246 3
# 7 -4.22 0.0000284 3
# 8 -4.20 0.0000327 3
# 9 -4.17 0.0000376 3
# 10 -4.14 0.0000432 3
# # ... with 391 more rows
Upvotes: 1
Reputation: 350
Use mutate and map2:
df %>%
mutate(data = map2(data, size,
function(x, y) mutate(x, size = y)))
Upvotes: 2