Making matrix in R - r

I want to make matrices without using loops such as for , while.
So I tried assigned k and put k in function which makes matrices.
powlist= function(base,startnum,endnum) (base)^(startnum:endnum)
m_maker= function(base) matrix(c(powlist(base,0,19)),4,5)
k= 2:10
a= m_maker((k-1)/k)
But function returns only one matrix.
I think function should return 9 matrices.
Please let me know how should I change this code.
I want to make each matrices that first one is matrix m_maker(1/2) and
second one m_maker(2/3) so on.
When I put k=2 and k=3 each time, it returns what I want.
What I want is way to return 9 matrices at one to go.

You're looking for lapply, like
res <- lapply((k-1)/k, m_maker)
However, you really should use an array for something like this.
ares <- abind(res, along=3)

Related

R: How to create a loop for, for a range of data in a function?

I have this parameter:
L_inf <- seq(17,20,by=0.1)
and this function:
fun <- function(x){
L_inf*(1-exp(-B*(x-0)))}
I would to apply this function for a range of value of L_inf.
I tried with loop for, like this:
A <- matrix() # maybe 10 col and 31 row or vice versa
for (i in L_inf){
A[i] <- fun(1:10)
}
Bur R respond: longer object length is not a multiple of shorter object length.
My expected output is a matrix (or data frame, or list maybe) with 10 result (fun(1:10)) for each value of the vector L_inf (lenght=31).
How can to do it?
You are trying to put a vector of 10 elements into one of the matrix cell. You want to assign it to the matrix row instead (you can access the ith row with A[i,]).
But using a for loop in this case is inefficient and it is quite straightforward to use one of the "apply" function. Apply functions typically return a list (which is the most versatile container since there is basically no constraint).
Here sapply is an apply function which tries to Simplify its result to a convenient data structure. In this case, since all results have the same length (10), sapply will simplify the result to a matrix.
Note that I modified your function to make it explicitly depend on L_inf. Otherwise it will not do what you think it should do (see keyword "closures" if you want more info).
L_inf_range <- seq(17,20,by=0.1)
B <- 1
fun <- function(x, L_inf) {
L_inf*(1-exp(-B*(x-0)))
}
sapply(L_inf_range, function(L) fun(1:10, L_inf=L))

How to assign submatrices in elements of a list

For example:
Let M be some matrix mXn matrix where n is large enough to make manual entry impossible.
tmp_list[1] <- M[,1:10]
tmp_list[2] <- M[,11:20]
.
.
.
tmp_list[last] <- M[end - 9,end]
The problem I'm working on is sort of monte carlo, repeating an experiment involving a random mXn matrix 100K times. I'm still pretty new to R, I've done it using a for loop, but it obviously took a very long time. So I'm hoping to assign each "experiment" to an element of a list and use lapply.
let's take the easy case, and you can expand it from there
say n=100, develop your start indeces
n<-100
byParam<-10
starts<-seq(1, n-(byParam-1), by=byParam)
then lapply
tmp_list<-lapply(starts, function(startIndex) M[, startIndex:(startIndex+(byParam-1)])
just one way to do it, becomes a bit more complicated if n is not a nice multiple of 10 (or whatever you set the "byParam" equal to). If that is the case then you can develop your start and end indeces, and then use mapply instead
#given start and end indeces
tmp_list<-mapply(function(startInd, endInd){
M[, startInd:endInd},
startInd=starts, endInd=ends)
Now lapply and mapply are still iterative, so I wouldn't expect massive improvement on time efficiency
EDIT
After discussion in the comments, here is a solution for the entire set up, not just the above question
tmp_list<-lapply(1:1000, function(i){
vect<-sample(c(0,1), 10*1000, replace=TRUE)
dim(vect)<-c(10, 1000)
vect
})
Let's break this down, it makes everything very simple.
We first create a random sample of 1's and 0's, of the length 10*1000 (the number of elements in each sub-matrix). We can then neatly convert that vector to a matrix by assigning it's dim attribute to be c(10, 1000), which changes its form to have 10 rows and 1000 columns. Then we return that into a list at the index i. We lapply over 1:1000, or iterate 1000 times.

iteratively create variable in for loop

I want to run a for loop that does a vector-matrix operation and returns a vector suffixed by the iteration number.
E.g:
If I have a 5 by 5 matrix , I want to take each column of the matrix at a time (at each iteration of the for loop) and work on a bunch of operations and at the end of it get a vector that is labelled as v_i where i refers to the column index and also the iteration number of the loop. I understand that this can be achieved in a for loop but I am not sure how to label the variable at each iteration.
For instance if I had to do this in SAS, I would have used v&i and put in a macro and run it. But not sure what is the R equivalent of this iterative labelling of variables.
Would really appreciate any help on this. I have a homework due next week and am in real crunch time.
Thanks!
It's not good programming practice to create objects out of a loop like that. It's better to put them in one object (say, a list) and populate the list from inside the loop. You can even create the list before running the loop.
I'm not sure if I understood correctly, but here's a very simple example that calculates the mean per column. To me, your question didn't actually reveal what you try to accomplish.
mat <- matrix(1:25, ncol=5)
lst <- as.list(numeric(ncol(mat)))
names(lst) <- sapply(1:ncol(mat), function(x) paste("v_",x,sep=""))
myfun <- mean
for(i in 1:ncol(mat)){
lst[[i]] <- myfun(mat[,i])
}
Cheers!
You'll be better served if you spend a bit of time learning how R works and how it is different from SAS. Lucky for you, there are resources dedicated to such a learning curve - see here.
In this case, you don't need to use a loop at all. I also doubt that you actually want a list output as SimonG suggests, rather a simple vector. Here's an example:
mat <- matrix(1:25, ncol=5)
#Give the matrix some names
colnames(mat) <- paste0("col_", 1:5)
#compute the column means
colMeans(mat)
---
col_1 col_2 col_3 col_4 col_5
3 8 13 18 23

Getting elements of a list in R

This is my problem:
There is a predefined list named gamma with three entries: gamma$'2' is 2x2 matrix gamma$'3' a 3x3 matrix and gamma$'4' a 4x4 matrix. I would like to have function that returns the matrix I need:
GiveMatrix <- function(n) {
gamma.list <- #init the list of matrices
gamma.list$n # return the list entry named n
Since n is not a character, the last line does not work. I tried gamma.list$paste(n)and gamma.list$as.character(n)but both did not work. Is there a function that converts nto the right format? Or is there maybe a much better way? I know, I am not really good in R.
You need to use:
gamma.list[[as.character(n)]]
In your example, R is looking for a entry in the list called n. When using [[, the contents of n is used, which is what you need.
I've found it!
gamma.list[as.character(n)] is the solution I needed.

Loop two variables one is conditional on another one

I want to make a loop which contains two variables i,j. for each i equals 1:24, j can be 1:24
but I don't know to make this loop;
i=1
while(i<=24)
{
j=seq(1,24,by=1)
for (j in j)
{
cor[i,j]
}
}
i=i+1
is this right? my output is cor[i,j].
In order to accomplish your final goal try...
cor(myMatrix)
The result is a matrix containing all of the correlations of all of the columns in myMatrix.
If you want to try to go about it the way you were it's probably best to generate a matrix of all of the possible combinations of your items using combn. Try combn(1:4,2) and see what it looks like for a small example. For your example with 24 columns the best way to cycle through all combinations using a for loop is...
myMatrix <- matrix(rnorm(240), ncol = 24)
myIndex <- combn(1:24,2)
for(i in ncol(myIndex)){
temp <- cor(myMatrix[,myIndex[1,i]],myMatrix[,myIndex[2,i]])
print(c(myIndex[,i],temp))
}
So, it's possible to do it with a for loop in R you'd never do it that way.
(and this whole answer is based on a wild guess about what you're actually trying to accomplish because the question, and your comments, are very hard to figure out)

Resources