【问题标题】:Assigning a weighted random variable to a new column in an R dataframe将加权随机变量分配给 R 数据框中的新列
【发布时间】:2022-08-17 02:15:31
【问题描述】:

我有一个在 R 中看起来像这样的数据框:

df1

date location daytype
2022-9-1 NT Thur
2022-9-2 NT Fri
2022-9-3 AP Sat
2022-9-4 AP Sun
2022-9-5 NT Mon

我想根据随机重量抽样为上午或下午班次创建一个新列:

df2

shift weight
Morning 0.8
Evening 0.2

有没有办法做到这一点?

df1$shift <- sample(df2, prob = df$weight)

    标签: r dataframe random dplyr


    【解决方案1】:

    我们可能需要将size指定为'df1'和replace = TRUE的行数

    df1$shift <-  with(df2, sample(shift, prob = weight, 
        size = nrow(df1), replace = TRUE))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-14
      • 2021-07-05
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      相关资源
      最近更新 更多