使用 purrr 为每一行创建 "sample" 列

Make column with "sample" for each row with purrr

我正在尝试为每一行数据制作带有样本值的列
但我是 purrr 的新手,做不到。
我的代码

df<-data.frame(x=rep(1:3,each=4),y=99)
df%>%
  group_by(x)%>%
  mutate_(val=~purrr::map_dbl(function(x) sample(50,1)))

这没有用。
但只有 purrr 的功能才有效:

1:5%>%purrr::map_dbl(function(x) sample(50,1))
[1] 39 30  7 18 45

感谢您的帮助!

你不需要呼噜声:

df <- data.frame(x = rep(1:3, each = 4), y = 99)

df %>%
  group_by(x) %>%
  mutate(val = sample(50, n()))

输出

# A tibble: 12 x 3
# Groups:   x [3]
       x     y   val
   <int> <dbl> <int>
 1     1  99.0    10
 2     1  99.0    25
 3     1  99.0     2
 4     1  99.0    24
 5     2  99.0    48
 6     2  99.0    19
 7     2  99.0    34
 8     2  99.0    33
 9     3  99.0    24
10     3  99.0    14
11     3  99.0    37
12     3  99.0    12

如果你需要使用purrr,我想你可以这样做:

dplyr::mutate(df, val = purrr::map(x, ~ sample(50, 1)))
   x  y val
1  1 99  35
2  1 99   4
3  1 99  43
4  1 99  28
5  2 99  49
6  2 99  31
7  2 99  31
8  2 99  31
9  3 99  19
10 3 99   4
11 3 99  43
12 3 99  20

或者用管道:

library(dplyr)
library(purrr)

df %>% 
  mutate(val = map(x, ~ sample(50, 1)))

数据:

df <- data.frame(x = rep(1:3, each = 4), y = 99)