【问题标题】:Create new variable based on factor levels and random selection根据因子水平和随机选择创建新变量
【发布时间】:2017-03-06 22:14:15
【问题描述】:

我在尝试使用 sample 函数来完成我的任务时有点卡住,即从因子的每个级别中抽取 n 个随机行并基于此创建一个新变量,另一个变量的值。

一个简化的例子:

Subject = c("100","100","100","100", "100", "200", "200", "200", "200", "200")
Condition = c("Blue","Blue","Blue","Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue")
Response = rnorm(10)
df = data.frame(Subject,Condition, Response) 

这里的目标是为Subject 的每个级别抽取 3 个随机行,创建一个新变量,比如说Condition.Rand,其中随机选择的行标记为“红色”,其余的行标记为任何值在Condition - 在这种情况下,“蓝色”。因此,对于每个SubjectCondition.Rand 的 60% 将标记为“红色”,40% 将标记为“蓝色”。

为了清楚起见,我希望 恰好 3 个随机行(或 5 个观察值的 60%)为主题 100 标记为“红色”,并且 完全 3 个随机行标记为主题 200 的“红色”。

谢谢!

【问题讨论】:

    标签: r variables random


    【解决方案1】:

    使用splitdf 划分为子组,并使用sample "Red""Blue" 为每个子组分配所需的概率。

    set.seed(42)
    do.call(rbind, lapply(split(df, df$Subject), function(a)
     cbind(a,
      cond.rand = sample(c("Red","Blue"), size = nrow(a), replace = TRUE, prob = c(0.6,0.4)))))
    #       Subject Condition   Response cond.rand
    #100.1      100      Blue -1.7813084      Blue
    #100.2      100      Blue -0.1719174      Blue
    #100.3      100      Blue  1.2146747       Red
    #100.4      100      Blue  1.8951935      Blue
    #100.5      100      Blue -0.4304691      Blue
    #200.6      200      Blue -0.2572694       Red
    #200.7      200      Blue -1.7631631      Blue
    #200.8      200      Blue  0.4600974       Red
    #200.9      200      Blue -0.6399949      Blue
    #200.10     200      Blue  0.4554501      Blue
    

    【讨论】:

    • 这不太有效,因为有时它会返回 all cond.rand 为给定主题标记为“红色”的实例。对于主题 100,我希望 恰好 3 个(或 60%)随机标记为“红色”的行,而对于主题 200,我希望 恰好 3 个随机标记为“红色”的行。
    【解决方案2】:

    我们也可以使用来自base Rave 来做到这一点

    set.seed(42)
    df1$cond.rand <-  with(df, ave(seq_along(Subject), Subject, FUN = function(x)
        sample(c("Red", "Blue"), size = length(x), replace = TRUE, prob = c(0.6, 0.4))))
    df1$cond.rand
    #[1] "Blue" "Blue" "Red"  "Blue" "Blue" "Red"  "Blue" "Red"  "Blue" "Blue"
    

    【讨论】:

    • 这和 d.b. 的建议有同样的问题。我将进行编辑以更清楚地解释我的任务。
    • @amurphy,试试with(df, ave(seq_along(Subject), Subject, FUN = function(x) sample(c(rep('Red', ceiling(length(x)*0.6)), rep('Blue', length(x) - ceiling(length(x)*0.6))))))
    • @d.b 非常感谢,就这样!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    相关资源
    最近更新 更多