我正在尝试为每行数据创建带有样本值的列
但是我是新手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)))
Run Code Online (Sandbox Code Playgroud)
这没用.
但功能purrr只有工作:
1:5%>%purrr::map_dbl(function(x) sample(50,1))
[1] 39 30 7 18 45
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
你不需要purrr:
df <- data.frame(x = rep(1:3, each = 4), y = 99)
df %>%
group_by(x) %>%
mutate(val = sample(50, n()))
Run Code Online (Sandbox Code Playgroud)
产量
# 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
Run Code Online (Sandbox Code Playgroud)