Hi ZRL, zrl wrote: > Dear list, > > I have a question regarding how to allocate or initialize the proper type of > the arrays or lists. > > I have a for loop, each iteration, I want it to assign a subset of a data > frame to an element of an array or list. > However, I am wondering how I should initialize or allocate the empty array > or list so that it has the same number of the elements as the subsets I am > going to assign and also make the data type is compatible to the subset I am > going to assign to it. > It should look like this: > > #initialize or allocate. ( I don't know how to) > { some codes: initialize an array or list (which one is better?) with "n" > elements} > > #"for" loop for assigning a subset of a large data frame to the elements of > the array or list (which on is better?) > for (i in 1: n){ > array[i] <- df[df$V1==A[i],] > }
You could let the software figure it out for you result = sapply(1:n, function(i, df, A) { df[df$V1==A[i],] }, df=df, A=A) or better (because you don't have to ensure that n is the length of A) if A is a vector result = sapply(A, function(a, df) { df[df$V1 == a, ] }, df=df) Martin > > > > > Thanks. > > ZRL > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.