【发布时间】: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