【问题标题】:Generate a data set with set means and variances based on Color根据颜色生成具有集合均值和方差的数据集
【发布时间】:2016-03-11 20:08:56
【问题描述】:

我有一个这个数据集structure(list(Color = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("blue", "green", "red" ), class = "factor")), .Names = "Color", row.names = c(NA, -30L ), class = "data.frame")

我想添加一个列,将平均值 5 和方差 2 分配给蓝色,将平均值 10 和方差 4 分配给绿色,将平均值 100 和方差 15 分配给红色..

【问题讨论】:

  • 这个答案有帮助吗?

标签: r data-generation


【解决方案1】:

如果您的数据按照示例中的方式排序,请为均值和标准偏差创建向量。然后在每个组上使用Map 调用rnorm

mus <- c(5, 10, 100)
sds <- c(2, 4, 15)
nums <- Map(function(n,mu, sd) rnorm(n, mu, sd), table(df1$Color), mus, sds)
df1$rndm <- unlist(nums)
df1
# Color       rndm
# 1   blue   5.048143
# 2   blue   8.159234
# 3   blue   7.029401
# 4   blue   3.298584
# 5   blue   3.388559
# 6   blue   3.125807
# 7   blue   3.428520
# 8   blue   3.659469
# 9   blue   7.881609
# 10  blue   3.483098
# 11 green   5.942954
# 12 green   3.172638
# 13 green  10.872443 

更新

要替换而不必排序将最后一行更改为:

df1[order(df1$Color),"rndm"] <- unlist(nums)

【讨论】:

  • 我的数据没有排序..有没有办法通过特定的颜色来做到这一点..?否则我应该可以对其进行排序..只是好奇。
  • 您可以添加 stack(nums) 它会为您排序,因为列表中有名称
  • 添加了另一种方式。
猜你喜欢
  • 2015-12-16
  • 2014-01-17
  • 2022-11-19
  • 1970-01-01
  • 2011-09-17
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
相关资源
最近更新 更多