I am trying to write a loop using "for" where my index,i, should have values from a set of values c(2,4,6,8,10,12) . I am further using i for subsetting values from another vector.
I defined a vector X , where X <- c(2,4,,6,8,10,12) ,
and then using for(i in X[1]:tail(X,n=1)).
This results in i taking all values from 2 to 12!
Whereas I want it to take the values mentioned in X only, i.e 2,4,6,8,10,12.
I hope someone can give me a hint how to do this
Thank you in advanced
You are looping through a sequence. If you want to loop only through the values of a vector, use this:
X <- c(2,4,6,8,10,12)
for(i in X) {
# Your code
}
Related
I have a vector of multiple values that I want to match to multiple values without the use of a loop. Is there a function that can do this?
x <- c(2,5,4)
y <- 2:10
which(x==y) #won't work
Expected output is 1,4,3
In my real use case, you can assume that there is only 1 correct match and it will match y every time. I need this to be as fast as possible, that's why I'm trying to avoid a loop. As a side note, this part is already inside of a foreach loop.
You want match
match(x,y)
# 1 4 3
The which() version would be which(x %in% y). But I don't think this fits for your purpose as the expected output is 1,2,3.
But if you apply which(y %in% x) than your output will be 1,3,4
I need to assign variables some values in a loop
Eg:
abc_1<-
abc_2<-
abc_3<-
.....
something like:
for(i in 1:20)
{
paste("abc",i,sep="_")<-some calculated value
}
I have tried to use paste as above but it doesn't work.
How could this be done.Thanks
assign() and paste0() should help you.
for example:
object_names <- paste0("abc",1:20)
for (i in 1:20){
assign(object_names[i],runif(40))
}
assign() takes the string in object_names and assigns the function in the second argument to each name. When you place a numeric vector inside of paste0() it gives back a character vector of concatenated values for each value in the numeric vector.
edit:
As Gregor says below, this is much better to do in a list because:
It will be faster.
When making a large number of things you probably want to do the same thing to each of them. lapply() is very good at this.
For example:
N <- 20
# create random numbers in list
abcs <- lapply(1:N,function(i) runif(40))
# multiply each vector in list by 10
abc.mult <- lapply(1:length(abcs), function(i) abcs[[i]] * 10)
I am a newbie to R, but avid to learn.
I have been trying endlessly to create a matrix with a variable element (in this case [2,2]). The variable element should take number 4 on the first run and 5 on the second (numbers).
This matrix would be multiplied by another matrix (N0) and produce a result matrix (resul).
Up so far, I have only been able to create the initial matrix with the variable element using a for loop, but I am having problems indexing the result matrix. I have tried several versions, but this is the latest. Any suggestions would be greatly appreciated. Thank you.
numbers <- c(4,5,length.out = 2)
A <- matrix(c(1,2,3,NA),nrow=2,ncol=2)
resul <- matrix(nrow=2,ncol=1)
for (i in 1:2) {
A[2,2]<- matrix(numbers[i])
N0 <- matrix(c(1,2),nrow=2,ncol=1)
resul[i,]<- A[i,i]%*%N0
}
Your code has two distinct problems. the first is that A[i,i] is a 1 x 1
matrix, so you're getting an error because your multiplying a 1 x 1 matrix
by a 2 x 1 matrix (N0).
you could either drop the subscript [i,i] and initialize the result to be
a two by two matrix like so:
result <- matrix(nrow=2,ncol=1)
for (i in 1:2){
A[2,2]<- matrix(numbers[i])
# a colunm vector
N0 <- matrix(c(1,2),
nrow=2,
ncol=1)
# note the index is on the column b/c `A%*%N0` is a column matrix
result[,i]<- A%*%N0
}
or you could either drop the the second subscript [i,] and initialize the result to be
a two by two matrix like so:
result <- matrix(nrow=2,ncol=1)
for (i in 1:2){
A[2,2]<- matrix(numbers[i])
# a colunm vector
N0 <- matrix(c(1,2),
nrow=2,
ncol=1)
result[i,]<- A[i,]%*%N0
}
but it's not clear from you post which (if either) answer is the correct one. Indexing is tricky :)
I have a problem in R trying to accumulate data that is gathered inside a for loop, that will iterate 200 + times before it ends, into a numeric vector defined before the loop starts. When the function returns the results it is apparent that the vector is only holding data from the last iteration of the loop. See the following pseudo codish example:
results <- numeric()
for(i in records)
a <- read a record in
b <- identify complete cases in a
c < sum(b)
if(c < 10)
d <- strip out rows with NAs in a
results <- cor(d[3:4])
endif
print results
end
One thing I am fairly certain of is that I need to some how define the length of "results" but the exact size is unknown until the function ends.
Any and all help will be appreciated.
As #Alex points out you can extend the vector like this:
results <- c(results, cor(d[3:4]))
or you can extend it implicitly like this:
results[i] <- cor(d[3:4])
or you can use the above line in conjunction with initializing the full
length vector like this:
results <- numeric(length(numeric()))
I have the following problem: I have a huge list of matrices with unique names that share the same dimension. I calculate some values that I now want to assign to a certain matrix indice, e.g. [3,4]. Because I have so many matrices I created a list with the names that those matrices shall have and then I used assign() to create all those matrices (empty). I would now like to call single matrices with its variable name to assign different values to certain matrix entries. I only know the commands assign() and eval(parse()), but didn't manage to get it working. I tried several things without success:
assign(x=MatrixNameList[i][3,4],value=z)
assign(x=MatrixNameList[i],value=z)[3,4]
eval(parse(text=MatrixNameList[i]))[3,4]<-z
assign(x=eval(parse(text=MatrixNameList[i]))[3,4] ,value=z)
So I am wondering if there is a possibility for what I want to do. The structure of my code is a simple loop:
Matrix1 <- Matrix2 <- matrix(nrow=3,ncol=4)
MatrixNameList <- c('Matrix1', 'Matrix2')
for (i in 1:length(MatrixNameList)){
z <- calculatedValue <- 4 # different for the single matrices
assign... ?
eval(parse... ?
}
I hope I was able to clearly point out my problem. Thanks in advance,
Eric
Use get:
get(MatrixNameList[1]) # retrieves matrix called "Matrix1"
However, you're better off collecting all those matrices into one object. Something like this should get you started.
Matrices <- lapply(MatrixNameList, get)
You can assign values like the following:
MatrixList <- list(Matrix1, Matrix2)
names(MatrixList) <- MatrixNameList
MatrixList[[1]][2,3] <- 4
# OR:
MatrixList$Matrix1[2,3] <- 4