【发布时间】:2015-05-01 09:22:28
【问题描述】:
我正在尝试在 tbl_df 中生成一列,它是 0 或 1 的随机整数。这是我正在使用的代码:
library(dplyr)
set.seed(0)
#Dummy data.frame to test
df <- tbl_df(data.frame(x = rep(1:3, each = 4)))
#Generate the random integer column
df_test = df %>%
mutate(pop=sample(0:1, 1, replace=TRUE))
但这似乎不像我预期的那样工作。我生成的字段似乎全为零。这是因为mutate 中的语句是并行评估的,因此最终使用相同的种子进行第一次随机抽取?
df_test
Source: local data frame [12 x 2]
x pop
1 1 0
2 1 0
3 1 0
4 1 0
5 2 0
6 2 0
7 2 0
8 2 0
9 3 0
10 3 0
11 3 0
12 3 0
在过去的几个小时里,我对此感到头疼。知道我的脚本有什么缺陷吗?
【问题讨论】:
-
使用
sample(0:1, 12, replace=TRUE) -
或
sample(0:1, n(), replace = TRUE)