选择数据帧的随机部分

时间:2015-11-11 17:46:10

标签: r

我的数据集是一系列调查。每项调查分为几个时间段,每个时间段都有几个观察时间。数据集中的每一行都是单个观察。它看起来像这样:

Survey     Period     Observation
  1.1        1            A
  1.1        1            A
  1.1        1            B
  1.1        2            A
  1.1        2            B
  1.2        1            A
  1.2        2            B
  1.2        3            C
  1.2        4            D

这是我的数据集的简化版本,但它证明了这一点(每个调查的几个时期,每个时期的几个观察)。我想要做的是在每次调查中制作一个由来自单个随机选择的时段的所有观测值组成的数据帧,以便在结果数据帧中每个调查只有一个周期,但所有相关的观测结果。我完全不知道这个,甚至不知道从哪里开始。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

如果我理解正确,每次调查都需要随机选择一个周期,然后获得所有相应的观察结果。 可能有其他方法,但我使用apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "22.0.1" defaultConfig { applicationId "jacobpihl.bluetoothcar" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.0' } 方法。

dplyr

答案 1 :(得分:1)

使用普通香草基地R做这样的事情,你可以以一种向前的方式实现你所需要的:

out = d[0,] # make empty dataframe with similar structure.
for( survey in levels( as.factor( d$Survey ) ) ) { # for each value of survey
  # randomly choose 1 from the observed values of Period for this value of Survey:
  period = sample( d[ d$Survey == survey, ]$Period, 1 )
  # attach all rows with that survey and that period to the empty df above
  out = rbind( out, d[ d$Survey == survey & d$Period == period, ] )
}