首页 > 解决方案 > 在 x 列下选择多行值 (a,b,c)

问题描述

我有一个包含 1617 个 obs 和 202 个变量的数据框,其中包括一个变量State。有52个独立国家。我想随机选择 5 个状态,但是这 5 个状态下的所有条目或对 5 个特定状态下的所有条目进行采样。

我试过用这个:

A <- subset(Iped, STABBR == c("PA", "DC", "MD", "DE", "VA"))

但它不会返回具有上述值的所有条目。它仅从大约 230 个条目中选择 45 个条目。

我希望能够子集包含 5 个状态并计算每个状态下的条目。

标签: rdplyr

解决方案


我可能无法完全理解您的问题,如果没有可重复的示例,它会变得更加困难。但这是data.table我认为您可以使用的解决方案:

# load library
require(data.table)

# define data:
set.seed(1)
states <- data.table(a = 1:1000, State = sample(LETTERS, 1000, TRUE))

# filter those states in a random sample of 5 (obviously not replacing them!): that's what gets before the first comma. Then count them (that's the .N) by the name of each State (that's the by):
states[State %in% sample(unique(State), 5, FALSE), .N, by = State]

推荐阅读