【问题标题】:What is the best way to generate a random dataset from an existing dataset?从现有数据集生成随机数据集的最佳方法是什么?
【发布时间】:2019-12-12 23:47:56
【问题描述】:

在给定预先存在的模板数据集的情况下,R 中是否有任何包可以生成随机数据集?

例如,假设我有 iris 数据集:

data(iris)
> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

我想要一些函数random_df(iris),它将生成一个与 iris 具有相同列但具有随机数据的数据帧(最好是保留原始某些统计属性的随机数据,(例如,数字的平均值和标准差)变量)。

最简单的方法是什么?


[来自问题作者的评论移至此处。 --编者注]

我不想从现有数据集中随机抽取行。我想生成与现有数据集具有所有相同列(和类型)的实际随机数据。理想情况下,如果有某种方法可以保留数字变量数据的统计属性,那将是可取的,但它不是必需的

【问题讨论】:

    标签: r


    【解决方案1】:

    这个开始怎么样:

    定义一个模拟来自df的数据的函数

    1. df 中的numeric 列的正态分布中抽取样本,均值和标准差与原始数据列中的相同,并且
    2. factor 列的级别统一抽取样本。
    generate_data <- function(df, nrow = 10) {
        as.data.frame(lapply(df, function(x) {
            if (class(x) == "numeric") {
                rnorm(nrow, mean = mean(x), sd = sd(x))
            } else if (class(x) == "factor") {
                sample(levels(x), nrow, replace = T)
            }
        }))
    }
    

    那么例如,如果我们取iris,我们得到

    set.seed(2019)
    df <- generate_data(iris)
    str(df)
    #'data.frame':  10 obs. of  5 variables:
    # $ Sepal.Length: num  6.45 5.42 4.49 6.6 4.79 ...
    # $ Sepal.Width : num  2.95 3.76 2.57 3.16 3.2 ...
    # $ Petal.Length: num  4.26 5.47 5.29 6.19 2.33 ...
    # $ Petal.Width : num  0.487 1.68 1.779 0.809 1.963 ...
    # $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 3 2 1 2 3 2 1 1 2 3
    

    扩展generate_data 函数以考虑其他列类型应该相当简单。

    【讨论】:

    • 这太棒了!谢谢!
    猜你喜欢
    • 2012-03-17
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多