i'm new user in R, and i'm trying to multiplicate elements of 2 vectors based on a loop and from that create n numbers of new vectors of this dataset
A = matrix(data= c(1, 2,3, 4, 5, 6, 7, 8, 9), nrow= 3, ncol= 3)
B = matrix(data= c(6, 1, 3), nrow= 1, ncol = 3)
C = matrix(data= c(5, 2, 2), nrow = 3, ncol= 1)
b.1 = matrix(data= NA, nrow = 1, ncol =ncol(A))
for (i in 1:ncol(B))
b.1[1, i] =((A[,i]%*%C[,ncol(C)]/A[nrow(A),i] ))
c.1 <- matrix(data = NA , nrow = nrow(C) , 1)
for (j in 1: nrow(C))
c.1[j, 1] = (A[j,]%*%B[nrow(B),]/A[j,ncol(A)])
b.2 <-matrix(data=NA, nrow= 1, ncol= ncol(A))
for (i in 1:ncol(A))
b.2[1, i] = ((A[,i]%*%c.1[,ncol(c.1)]/A[nrow(A),i] ))
c.2 <- matrix(data= NA, nrow = nrow(C), ncol= 1)
for (j in 1: nrow(C))
c.2[j,1] = (A[j,]%*%b.1[nrow(b.1),]/A[j,ncol(A)])
Until this part, the code works, but i can't use this double loop, did anyone knows why? Thanks in advance
##c.x y b.x
for x in 3:10{
b.[x] <-matrix(data=NA, nrow= 1, ncol= ncol(A))
for (i in 1:ncol(A))
b.[x][1, i] = ((A[,i]%*%c.[x-1][,ncol(c.1)]/A[nrow(A),i] ))
c.[x] <- matrix(data= NA, nrow = nrow(C), ncol= 1)
for (j in 1: nrow(C))
c.[x][j,1] = (A[j,]%*%b.[x-1][nrow(b.[x-1]),]/A[j,ncol(A)])
CodePudding user response:
Your exact problem is a little complicated, so I will simplify so you can see what is not working, and how you can go about making your specific code work.
##c.x y b.x
for(x in 3:10){
b.[x] <-matrix(data=NA, nrow= 1, ncol= ncol(A))
}
# Error: object 'b.' not found
Why is b.
not found? you haven't specified it. In R b.1 and b.2 are not subsets of the same object, they are completely independent objects.
To assign new objects a name in a loop, you can use something like this:
for(x in 3:10){
assign(paste0("b.",x), matrix(data=NA, nrow= 1, ncol= ncol(A)) )
}
So now we've created objects named b.3
, b.4
, b.5
, ..., b.10
, but you still aren't able to simple call b.[x]
within a loop, because that appears to be an object named b.
and the xth element in that object, which isn't what you are trying to do.
You have to get()
the object (now that the objects are created with the last step):
for(x in 3:10){
temp<-get(paste0("b.",x))
print(temp)
}
[,1] [,2] [,3]
[1,] NA NA NA
[,1] [,2] [,3]
[1,] NA NA NA
[,1] [,2] [,3]
[1,] NA NA NA
[,1] [,2] [,3]
[1,] NA NA NA
[,1] [,2] [,3]
[1,] NA NA NA
[,1] [,2] [,3]
[1,] NA NA NA
[,1] [,2] [,3]
[1,] NA NA NA
[,1] [,2] [,3]
[1,] NA NA NA
A silly example adding to columns and then dataframes iteratively in nested for loops:
for(x in 3:10){
assign(paste0("b.",x), matrix(data=NA, nrow= 1, ncol= ncol(A)) )
temp<-get(paste0("b.",x))
for(i in 1:ncol(A)){
temp[1, i]<-paste("whatever you want ",i)
}
assign(paste0("b.",x),temp)
}
Now let's look at one of the dataframes b.4
(although with this code each is the same):
b.4
[,1] [,2] [,3]
[1,] "whatever you want 1" "whatever you want 2" "whatever you want 3"
So you cannot just add to an object with .
like you might in other languages.