2016-10-21 8 views
0

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),] 

    } 

} 

何も起こりません。私は何が欠けていますか?

おかげ

+1

あなたの関数は値を返しません。例えば、最後の2つのカッコの間に 'df'を追加して' df'を親環境に返します。 – eipi10

+0

@ eipi10真実、私のサンプルを環境に現われる方法を知っていますか? – Zyferion

+0

ループの繰り返しごとに 'df'だけでなく' sample'の値も返したいと思っていますか?ところで、 'x = assign(paste(" ds "、i、sep =" ")、sample)'は必要ありません。これは 'x = sample'と等価です。しかし、あなたは 'df = df [!(df $ row%in%sample $ row)、]'を実行できるので、その必要はありません。 – eipi10

答えて

3

ちょうどリストに結果を保存し、それを返します。同様のデータフレームを使用して環境を混乱させるのではなく、地球環境にサンプルのリストである単一のオブジェクトがあります。

あなたはdfで何をしようとしているのかよく分かりませんが、ここではすべてのサンプルを返す方法があります。私はあなたがdfで何をしたいのか知っていると私は同様にそれを追加することができます:あなたが明示的に1を返す場合を除き

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) 
} 
+0

ありがとう、ちょうど私が必要としたものです。私はリストを忘れてしまった。 – Zyferion

関連する問題