Reputation: 109
How can I store values in R? I want to generate four values of K
and store it in m[1]
so I have m[1,1]
, m[1,2]
, m[1,3]
, m[1,4]
. Then generate the 2nd set of four values of K
and store in m[2]
so that I have m[2,1]
, m[2,2]
, m[2,3]
, m[2,4]
. I tried this program but I get this error message:
1: In m[j] = Cp[1:4] :
number of items to replace is not a multiple of replacement length
2: In m[j] = Cp[1:4] :
number of items to replace is not a multiple of replacement length
k=numeric()
k[1]=0
for (j in 1:2) {
for (count in 1:3) {
k[count+1]=k[count]+rnorm(1,0,1)
}
m[j]=k[1:4]
}
Upvotes: 0
Views: 117
Reputation: 1647
while josilber's answer is nicely put in R-speak (and I'd suggest using it), to understand why your code isn't working think of the following.
m isn't defined anywhere, prior to the loop, but assume it is defined as a numeric(), like k, which means it is a vector.
You make the call
m[j]<-k[1:4]
When using single brackets to subset a vector, in your example it will in essence return m[j] (which is a single number), and attempt to replace it with k[1:4] (which is 4 numbers!).
That doesn't make a whole lot of sense, so R complains about it. The only way this would work is if you tried to replace 4 numbers with 4 numbers (things have to be of equal length with single brackets, or actually a multiple of each other, but that deals with recycling and we probably don't want to get into that here)
What you could do instead is define m as a list (m<-list()) You would then change your call to
m[[j]]<-k[1:4]
In R, lists don't care about the size of individual elements, each slot is its own bucket. To access a bucket, you use double brackets instead of single. Lists of lists work too! So if you were to use lists of lists, you'd be able to get the two dimensional aspect you want in your question, where each inner bucket, m[[i, j]], would be equal to the associated k[1:4]
Upvotes: 1
Reputation: 44320
Your rows are the cumulative sum of samples from the normal distribution; you can get this with something like:
set.seed(144)
t(sapply(1:2, function(row) c(0, cumsum(rnorm(3, 0, 1)))))
# [,1] [,2] [,3] [,4]
# [1,] 0 -1.650556 -1.047746 -1.521630
# [2,] 0 -1.797613 -3.218734 -3.059847
Upvotes: 1