【问题标题】:R: Why won't my function create objects in my environmentR:为什么我的函数不会在我的环境中创建对象
【发布时间】:2016-10-21 03:41:10
【问题描述】:

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

在此示例中,我使用的是 iris 数据集。 iris 数据集有 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 返回到父环境。
  • @eipi10 true,你知道如何让我的样本出现在环境中吗?
  • 您的意思是您不仅要返回df,还要为循环的每次迭代返回sample 的值?顺便说一句,不需要x = assign(paste("ds",i,sep=""),sample)。这相当于x = sample。但也不需要这样做,因为你可以这样做df = df[!(df$row %in% sample$row),]
  • 我希望样本 ds1,ds2... 成为我的环境中出现的对象。有点像如果我在没有函数的情况下正常运行循环会发生什么。
  • 我认为您可能应该返回一个列表以避免混乱您的环境,其中列表的每个元素都是 ds1、ds2...

标签: r function for-loop sampling


【解决方案1】:

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

我不确定你想用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)
}

【讨论】:

  • 是的,谢谢,正是我需要的。我忘记了列表。
猜你喜欢
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 2021-06-30
  • 1970-01-01
相关资源
最近更新 更多