【问题标题】:Rename column elements from sampled vector sequentially in R在R中按顺序重命名采样向量中的列元素
【发布时间】:2021-03-31 17:07:43
【问题描述】:

从具有 230 行权重(唯一权重 = 9)的文件中,在 R 中对以下权重进行采样:

5、9、7、2、8、6、2、2、2

使用 for 循环、一个空矩阵和一个包含我的完整数据集的输入文件,这些权重创建以下数据框(完整采样的数据框约为 230 行):

WeightSample <- structure(list(Type = c("Apple", "Banana", "Apple", "Apple", 
"Banana", "Orange", "Pear", "Banana", "Pear", "Pear", "Banana", 
"Pear", "Pear"), Color = c("Red", "Yellow", "Red", "Red", "Yellow", 
"Orange", "Green", "Yellow", "Green", "Green", "Yellow", "Green", 
"Green"), Weight = c(5L, 5L, 5L, 9L, 9L, 7L, 2L, 8L, 6L, 2L, 2L, 2L, 2L)), 
class = "data.frame", row.names = c(NA, -13L))

我需要的数据框:

WeightSampleNeed <- structure(list(Type = c("Apple", "Banana", "Apple", "Apple", 
"Banana", "Orange", "Pear", "Banana", "Pear", "Pear", "Banana", 
"Pear", "Pear"), Color = c("Red", "Orange", "Yellow", 
"Red", "Green", "Green", "Red", "Yellow", "Red", "Green", "Red", "Orange", "Yellow"), 
Weight = c(1L, 1L, 1L, 2L, 2L, 3L, 4L, 5L, 6L, 7L, 7L, 8L, 9L)), 
class = "data.frame", row.names = c(NA, -13L))

我试过了:

library(data.table)
setDT(WeightSample)[, num := rleid(WeightSample$Weight)]

由于此代码在组更改时分配了一个连续数字,因此它不会在我的采样权重向量末尾拾取 2、2、2,而是应该用连续数字(即 7、8 和9) 对于与采样向量中的权重相关联的每一行数据。我从我的完整数据集中对权重进行了 1000 次采样,因此,每个新数据帧的行数都会发生变化。因此,我对基于位置的代码是否可行感到犹豫。任何帮助将不胜感激。

【问题讨论】:

  • 为什么前 5 5 5 或 9 9 没有变化,最后只应该变化 2
  • 您是否有任何关于唯一值 5, 9, 7, 2, 8, 6, 2, 2, 2 的信息,因为“WeightSample”没有显示该信息
  • 我理解那部分,但你如何区分最后的 2、2、2。我建议使用一个命名向量进行映射,因为在输入中不清楚如何区分 2 和另一个
  • 可能在您的原始采样代码中,这应该是一个命名向量,即v1 &lt;- setNames(c(5, 9, 7, 2, 8, 6, 2, 2, 2), seq_len(9)),然后您返回“v1”的名称而不是值,以便获得预期

标签: r


【解决方案1】:

也许在原始代码中,我们将“Weight”更改为“Fruit.sample”的names

for (i in 1:1000) {
 
   Fruit.sample <- sample(AllFruit$Weight, size = 9, 
          replace = TRUE) #create a sample based on weight of fruit
   # // set the names of Fruit.sample as the sequence of those values
   names(Fruit.sample) <- seq_along(Fruit.sample)
   WeightSample <- NULL

for (k in seq_along(Fruit.sample)) {

    tmp <- AllFruit[which(AllFruit$Weight == Fruit.sample[k]),]
    # // replace the 'Weight' with the corresponding `names` of Fruit.sample
    tmp$Weight <- names(Fruit.sample[k])
    WeightSample <- rbind(WeightSample, tmp)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多