【问题标题】:Want to generate 100 samples and label each sample as 0 or 1 based on a coin flip R想要生成 100 个样本并基于硬币翻转 R 将每个样本标记为 0 或 1
【发布时间】:2023-03-29 00:19:01
【问题描述】:

我想生成 100 个样本,然后根据随机硬币翻转为每个样本分配 0 或 1 的标签。因此,如果我翻转正面,则我将样本分配为 0,而对于尾部,我将分配样本为 1。

到目前为止我有:

n = 100
for (ii in 1:n){
  sample(n)[ii] #access one sample at a time 
}

但我不确定如何将硬币翻转方面分配给每个样本。

【问题讨论】:

  • 代码可能不是你想要的,看看sample(5) 给出了什么(整数1:5 的排列)。然后你取 n 个这样的排列中的每一个的 iith 元素。要对 n 个二进制值进行采样,请使用 rbinom(n, 1, prob = 0.5)
  • 你想要cbind(sample(n), rbinom(n, 1, prob = 0.5))吗?

标签: r classification logistic-regression sampling coin-flipping


【解决方案1】:

您没有指定所需输出的数据格式。此解决方案使用一个数据框,将每个样本放在一行中,并添加一个 label 列以包含随机 0/1。

n 更改为 100 而不是 5 以获得您的结果。

n <- 5
# Create n samples; result is matrix m with each row being one sample
m <- t(sapply(rep(n, n), sample))
# Convert to data frame - obviously
df <- as.data.frame(m)
# identify samples
rownames(df) <- paste0("sample", 1:n)
# add a name column to df that contains a 0/1 random variable
df$label <- sample(0:1, n, replace = TRUE)
df
#>         V1 V2 V3 V4 V5 label
#> sample1  2  4  5  1  3     0
#> sample2  3  2  1  5  4     1
#> sample3  4  2  1  5  3     0
#> sample4  2  1  5  3  4     0
#> sample5  3  4  2  1  5     1

reprex package (v1.0.0) 于 2021-02-18 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多