采样方向错误 R

Sampling in the wrong direction R

背景

我有两个变量,分别叫做xy请看图片下面的R代码)。当我 plot(x, y) 时,我获得了 顶行图(见下文)y 值 堆叠在 每个 x 值 的顶部。然后我尝试 从这些 y 值中抽样 并在母图下方制作第二个图。

问题

我想知道为什么当我使用 predit.range见下面的 R 代码)时 10:0(当我使用 0:10) 我的抽样程序完全走错了方向?请比较顶行图和底行图情节)

############# Input Values ################
                      each.sub.pop.n = 150; 
                      sub.pop.means = 20:10; 
                      predict.range = 10:0; 
                      sub.pop.sd = .75;
                      n.sample = 2;
#############################################
par( mar = c(2, 4.1, 2.1, 2.1) )

m = matrix( c(1, 2), nrow = 2, ncol = 1 ); layout(m)

Vec.rnorm <- Vectorize(function(n, mean, sd) rnorm(n, mean, sd), 'mean')

y <- c( Vec.rnorm(each.sub.pop.n, sub.pop.means, sub.pop.sd) )

x <- rep(predict.range, each = each.sub.pop.n)

plot(x, y)

## Unsuccessful Sampling ## The problem must be lying in here:

sampled <- lapply(split(y, x), function(z) sample(z, n.sample, replace = TRUE))
sampled <- data.frame(y = unlist(sampled), 
                 x = rep(predict.range, each = n.sample))
plot(sampled$x, sampled$y)

这足以说明原因。

x <- 10:0; y <- 10:0

你注意到了吗

split(y, x)

对列表进行排序?要获得您想要的顺序,请控制因素水平:

split(y, factor(x, levels = unique(x))

在您的上下文中,您可以在没有 unique 的情况下高效使用:

split(y, factor(x, levels = predict.range))