繁体   English   中英

R:为什么我的函数不能在我的环境中创建对象

[英]R: Why won't my function create objects in my environment

我想编写一个函数,该函数将创建n个数据集的随机样本而无需替换。

在此示例中,我使用虹膜数据集。 虹膜数据集有150个观测值,说我要10个样本。

我的尝试:

#load libraries
library(dplyr)    

# load the data
data(iris)
head(iris)

# name df
df = iris

# set the number of samples
n = 10

# assumption: the number of observations in df is divisible by n
# set the number of observations in each sample
m = nrow(df)/n

# create a column called row to contain initial row index
df$row = rownames(df)

# define the for loop
# that creates n separate data sets
# with m number of rows in each data set

for(i in 1:n){
  # create the sample
  sample = sample_n(df, m, replace = FALSE) 

  # name the sample 'dsi'
  x = assign(paste("ds",i,sep=""),sample)

  # remove 'dsi' from df
  df = df[!(df$row %in% x$row),]

}

当我运行这段代码时,我得到了想要的。 我得到了名为ds1,ds2,...,ds10的随机样本。

现在,当我尝试将其转换为功能时:

samplez <- function(df,n){

  df$row = rownames(df)

  m = nrow(df)/n

  for(i in 1:n){

    sample = sample_n(df, m, replace = FALSE) 

    x = assign(paste("ds",i,sep=""),sample)

    df = df[!(df$row %in% x$row),]

  }

}

当我执行“ samplez(iris,10)”时,什么也没有发生。 我想念什么?

谢谢

只需将结果保存在列表中并返回即可。 然后,您将在全局环境中只有一个对象,即样本列表,而不是用一堆类似的数据框使环境杂乱无章。

我不确定您要使用df做什么,但是这里是如何返回所有样本的方法。 让我知道您想使用df做什么,我也可以添加它:

samplez <- function(df,n){

  samples = list()

  df$row = rownames(df)

  m = nrow(df)/n

  for(i in 1:n){

    samples[[paste0("ds",i)]] = sample_n(df, m, replace = FALSE) 

    df = df[!(df$row %in% samples[[i]]$row),]

  }
  return(samples)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM