【问题标题】:Random sample from multiple columns [closed]来自多列的随机样本[关闭]
【发布时间】:2020-09-22 09:14:51
【问题描述】:

我有一个包含多列的数据集,其中每一行代表一个产品,每一列包含对相应产品的一个评论。对于每个产品,我们观察到多个 cmets,每个 cmets 都存储在自己的列中。

现在我想通过以下方式创建两个新数据集: (1) 一个只有一列的数据集,包括从多个评论列中随机抽取的 x (个) cmets 样本。 (2) 与 (1) 一样,但现在我想从每列中采样相同数量的 cmets(例如,“comment1”中的 2 个 cmets 和“comment2”中的 2 个 cmets。

Example data:
commentda = data.frame(product_id = c(1,2,3,4), comment1 = c("Very good", "Bad", "Would buy it", "Zero stars"), comment2 = c("Bad reputation", "Good seller", "Great service", "I will buy it again"))
> 
> commentda
  product_id     comment1            comment2
1          1    Very good      Bad reputation
2          2          Bad         Good seller
3          3 Would buy it       Great service
4          4   Zero stars I will buy it again

【问题讨论】:

  • 到目前为止,您的“问题”不包含任何问题或代码来帮助您。您可能需要相应地更新您的问题。

标签: r function text dplyr sample


【解决方案1】:

您可以获得长格式的数据,这将有助于有效地进行此类操作。

library(dplyr)
n <- 2

long_data <- commentda %>%  tidyr::pivot_longer(cols = starts_with('comment'))
  1. 包含随机n cmets
long_data %>% slice_sample(n = n)
  1. 从每列随机包含n cmets。
long_data %>%  group_by(name) %>%  slice_sample(n = n)

【讨论】:

  • 谢谢! slice_sample 是 dplyr 函数吗?我试过 ??slice_sample 但 R 告诉我它没有找到任何结果。
  • 是的,它在dplyr 1.0.0 以上版本中可用。如果您有旧版本,您可以使用sample_n,即sample_n(size = n)
猜你喜欢
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 2020-09-08
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
  • 1970-01-01
相关资源
最近更新 更多