R:为什么我的函数不能在我的环境中创建对象
R: Why won't my function create objects in my environment
我想编写一个函数来创建 n 个数据集的随机样本而无需替换。
在这个例子中,我使用的是 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)' 时没有任何反应。我错过了什么?
谢谢
只需将结果保存在列表中,然后 return。然后您将在您的全局环境中拥有一个对象,即示例列表,而不是用一堆相似的数据框使您的环境变得混乱。
我不确定您要用 df
做什么,但这里是 return 所有示例的方法。让我知道您想用 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)
}
我想编写一个函数来创建 n 个数据集的随机样本而无需替换。
在这个例子中,我使用的是 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)' 时没有任何反应。我错过了什么?
谢谢
只需将结果保存在列表中,然后 return。然后您将在您的全局环境中拥有一个对象,即示例列表,而不是用一堆相似的数据框使您的环境变得混乱。
我不确定您要用 df
做什么,但这里是 return 所有示例的方法。让我知道您想用 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)
}