indexing in loops: var[x+1] subscript out of bounds - r

I'm creating and storing a bunch of conditional matrices in vector form then I'm recalling them, returning their structure to matrix, and multiplying by a vector. This vector depends on the previous vector and the current matrix. I have tried to express this in the second loop as [,y+1] to index the vectors on the output matrix . While I get the desire result, I also get an error that aborts the program. I would appreciate suggestions on how to approach this.
env=rnorm(50, 22, 5)
les=matrix(nrow=9,ncol=length(env),byrow=T)
for (x in 1:length(env))
{
a=sqrt(env[x])-3
b=sqrt(env[x])-2
c=sqrt(env[x])-1
A=.9
B=.5
C=.2
les[,x]=c(a,b,c,A,0,0,0,B,0)
}
pop=matrix(nrow=3,ncol=length(env))
pop[,1]=c(1,2,2)
for (y in 1:length(env))
{
pop[,y+1]=pop[,y]%*%matrix(les[,y],3,3,T)
}
print(pop)
barplot(pop)

Vector, matrix and array subscripting in R is all 1-based. You need to iterate only up to length(env)-1 if you are going to regerence ahead by 1 inside the loop.

Related

R Apply a function to matrix where each vector (row) is an argument

I am trying to write a function to apply a function to each row in a matrix, but the problem is I need each vector(row) in the matrix to be used as an argument for the function. I'm using sapply so I can store it as a result matrix and sort it.
What I have so far is
r=apply(m,1,cosineSim(x['word',]))
where cosineSim is defined as
cosineSim <- function(v1,v2){
a <- sum(v1*v2)
b <- sqrt(sum(v1*v1))* sqrt(sum(v2*v2))
return(a/b)
}
But the problem I'm having is I can't figure out how to use each vector that's being applied as an argument for the cosine function which takes two vectors. I have one vector, but the second is supposed to be the current row that the apply function is on. I'm new to R so please forgive me if my solution is trivial. Thanks for any help.
Some sample data I'm working with includes:
the 0.41800 0.249680 -0.41242 0.121700 0.345270 -0.044457 -0.49688 -0.178620 -0.00066023 -0.656600 0.278430 -0.14767 -0.55677 0.14658 -0.0095095
. 0.15164 0.301770 -0.16763 0.176840 0.317190 0.339730 -0.43478 -0.310860 -0.44999000 -0.294860 0.166080 0.11963 -0.41328 -0.42353 0.5986800
of 0.70853 0.570880 -0.47160 0.180480 0.544490 0.726030 0.18157 -0.523930 0.10381000 -0.175660 0.078852 -0.36216 -0.11829 -0.83336 0.1191700
to 0.68047 -0.039263 0.30186 -0.177920 0.429620 0.032246 -0.41376 0.132280 -0.29847000 -0.085253 0.171180 0.22419 -0.10046 -0.43653 0.3341800
and 0.26818 0.143460 -0.27877 0.016257 0.113840 0.699230 -0.51332 -0.473680 -0.33075000 -0.138340 0.270200 0.30938 -0.45012 -0.41270 -0.0993200
in 0.33042 0.249950 -0.60874 0.109230 0.036372 0.151000 -0.55083 -0.074239 -0.09230700 -0.328210 0.095980 -0.82269 -0.36717 -0.67009 0.4290900
This is a small example of the matrix I'm working with and I'm trying to use each of those rows as a vector for my cosineSim function.

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

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.

For loop over unique values

Is it possible to write a for loop with discrete levels?
I have a vector of the following form:
a<-c(1,1,1,1,1,3,3,5,11,18 ....1350)
it is an increasing series but does not follow any logical order;
I would like to run a for loop using levels(a) as an argument:
for i in 1:levels(a)
I get the following error:
In 1:levels_id :
numerical expression has 1350 elements: only the first used
Your initial mistake is that you are confusing looping over the index with looping over the elements of your vector.
If you want to loop over unique elements of your vector then use:
for(i in unique(a))
I assume that's what you wanted to do. But the alternative is to loop over the unique vector's index:
for(i in 1:length(unique(a))){
this.a <- unique(a)[i]
}
These two are equivalent, but the second will enable you to know the current index as well (if you ever needed it).

nrow(matrix) function

I have assignment using R and have a little problem. In the assignment several matrices have to be generated with random number of rows and later used for various calculations. Everything works perfect, unless number of rows is 1.
In the calculations I use nrow(matrix) in different ways, for example if (i <= nrow(matrix) ) {action} and also statements like matrix[,4] and so on.
So in case number of rows is 1 (I know it is actually vector) R give errors, definitely because nrow(1-dimensional matrix)=NULL. Is there simple way to deal with this? Otherwise probably whole code have to be rewritten, but I'm very short in time :(
It is not that single-row/col matrices in R have ncol/nrow set to NULL -- in R everything is a 1D vector which can behave like matrix (i.e. show as a matrix, accept matrix indexing, etc.) when it has a dim attribute set. It seems otherwise because simple indexing a matrix to a single row or column drops dim and leaves the data in its default (1D vector) state.
Thus you can accomplish your goal either by directly recreating dim attribute of a vector (say it is called x):
dim(x)<-c(length(x),1)
x #Now a single column matrix
dim(x)<-c(1,length(x))
x #Now a single row matrix
OR by preventing [] operator from dropping dim by adding drop=FALSE argument:
x<-matrix(1:12,3,4)
x #OK, matrix
x[,3] #Boo, vector
x[,3,drop=FALSE] #Matrixicity saved!
Let's call your vector x. Try using matrix(x) or t(matrix(x)) to convert it into a proper (2D) matrix.

Resources