在数据帧中组合向量和列表列

时间:2018-01-30 18:28:05

标签: r tidyverse purrr

我正在尝试确定如何将列作为矢量添加到列中,该列是同一数据框中的列表

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)
  )

使用上面的结果,我想在dens_est数据框中添加一列,其中包含size列的关联值。

2 个答案:

答案 0 :(得分:2)

使用mutate和map2:

A   B 
80  2.08

答案 1 :(得分:1)

我们可以使用map2遍历dens_estsize列,并使用mutate为每个数据框创建size列。

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