nのデータセットの無作為サンプルを置き換えずに作成する関数を作成したいとします。R:自分の関数が自分の環境内でオブジェクトを作成しない理由
この例では、虹彩データセットを使用しています。 アイリスデータセットには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(アイリス、10)' を実行したとき
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),]
}
}
何も起こりません。私は何が欠けていますか?
おかげ
あなたの関数は値を返しません。例えば、最後の2つのカッコの間に 'df'を追加して' df'を親環境に返します。 – eipi10
@ eipi10真実、私のサンプルを環境に現われる方法を知っていますか? – Zyferion
ループの繰り返しごとに 'df'だけでなく' sample'の値も返したいと思っていますか?ところで、 'x = assign(paste(" ds "、i、sep =" ")、sample)'は必要ありません。これは 'x = sample'と等価です。しかし、あなたは 'df = df [!(df $ row%in%sample $ row)、]'を実行できるので、その必要はありません。 – eipi10