【问题标题】:Take random samples based on two groups in r基于 r 中的两组随机抽样
【发布时间】:2021-07-02 02:48:45
【问题描述】:

我有两列数据;身份证和专业。每个 ID 都有两次出现,并且出现了唯一的专业。我想从每个专业组中随机抽取 400 个数据样本,其中出现 2 次 ID。我已经尝试使用 sample_n 进行 dplyr 组,但它会以不同的出现次数转换 ID。

数据示例

specialty <- c("obs", "obs", "ped", "ped", "im", "im", "obs", "obs")
ID <- c("M", "M", "K", "K", "l", "l", "N", "N")
shift <- c("night", "day", "night", "day", "night", "day", "night", "day")

如果我对每个专业抽取 2 个样本,我想要的输出是

specialty <- c("obs", "obs", "im", "im", "ped", "ped")
ID <- c("M", "M", "l", "l", "K", "K")
shift <- c("night", "day", "night", "day", "night","day")

我得到的是

specialty <- c("obs", "obs", "im", "im", "ped", "ped")
ID <- c("M", "M", "l", "k", "k", "N")
shift <- c("night", "day", "night", "night", "day", "day")

【问题讨论】:

  • 除了编辑问题之外,您是否可以在答案部分中将下面的答案与您使用的代码一起包含在内?将来可能会对其他人有所帮助。

标签: r random


【解决方案1】:

更新 我想出了一个解决办法。我已经连接了具有相似 ID 的每 2 个连续行,然后按专业进行采样。最后,我有表示连续行的子集列并将它们绑定为行。

specialty <- c("obs", "obs", "ped", "ped", "im", "im", "obs", "obs")
ID <- c("M", "M", "K", "K", "l", "l", "N", "N")
shift <- c("night", "day", "night", "day", "night", "day", "night", "day")
d <- data.frame(specialty, ID, shift)

library(dplyr)
library(sqldf)
d2 <- subset(d, d$shift == "night")
d3 <- subset(d, d$shift == "day")
d4 <- sqldf("select * from d2 left join d3 on d2.ID = d3.ID", row.names = TRUE)
d5 <- d4 %>% 
      group_by(specialty)  %>%
      sample_n(size = 1)
d6 <- d5[, 1:3]
d7 <- d5[, 4:6]
colnames(d7) <- sub(".1", "", colnames(d7))
d8 <- rbind(d6, d7)
d8

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    相关资源
    最近更新 更多