How can I create a vector of matrices of different dimension in R. For example say I have two matrices
M1=array(0,dim=c(2,2))
M2=array(0,dim=c(3,3))
Then I can make a vector C containing these matrices such that
C[1]=M1
and
C[2]=M2.
I know that I can create a 3 dimensional array
C=array(NA,dim=c(2,3,3)
but the only way I know how to do this has to have the
C[1,,]
element in the array have more space then necessary.
Use a list
C <- list()
C[[1]] <- array(0,dim=c(2,2))
C[[2]] <- array(0,dim=c(3,3))
C[[1]][1,1] <- 5
C[[1]]
C[[2]]
Related
I have a large list of 2 elements containing lists of species containing lists of 25 vectors, resembling a set like this:
l1 <- list(time=runif(100), space=runif(100))
l2 <- list(time=runif(100), space=runif(100))
list1 <- list(test1=list(species1=l1, species2=l2),test2=list(species1=l1, species2=l2))
I think, its essentially a list of a list of lists.of vectors.
I want to create a data.frame from all space-vectors of all 'species' in just one of the two sublists:
final <- as.data.frame(cbind(unlist(list1[[2]]$species1$space), unlist(list1[[2]]$species2$space)))
names(final) <- names(list1[[2]])
Essentially, i need a loop/apply command that navigates me through list1[[2]]$species and picks all vectors called space.
Thank you very much!
We can use a nested loop to extract the 'space' elements
data.frame(lapply(list1, function(x)
sapply(x, "[", 'space')))
I'm subsetting different arrays which sometimes take dimension (x,y=1,z). In these cases R automatically converts the array into a matrix and I would like to avoid it if possible keeping the structure (x, y, z').
Here's an example:
a = array(rnorm(2*1*10), c(2,1,10)) # a is an array
b = a[,,3:5] # b is a matrix
You can use drop=FALSE
a[,,3:5, drop=FALSE]
I've done a little bit of digging for this result but most of the questions on here have information in regards to the cbind function, and basic matrix concatenation. What I'm looking to do is a little more complicated.
Let's say, for example, I have an NxM matrix whose first column is a unique identifier for each of the rows (and luckily in this instance is sorted by that identifier). For reasons which are inconsequential to this inquiry, I'm splitting the rows of this matrix into (n_i)xM matrices such that the sum of n_i = N.
I'm intending to run separate analysis on each of these sub-matrices and then combine the data together again with the usage of the unique identifier.
An example:
Let's say I have matrix data which is 10xM. After my split, I'll receive matrices subdata1 and subdata2. If you were to look at the contents of the matrices:
data[,1] = 1:10
subdata1[,1] = c(1,3,4,6,7)
subdata2[,1] = c(2,5,8,9,10)
I then manipulate the columns of subdata1 and subdata2, but preserve the information in the first column. I would like to combine this matrices again such that finaldata[,1] = 1:10, where finaldata is a result of the combination.
I realize now that I could use rbind and the sort the matrix, but for large matrices that is very inefficient.
I know R has some great functions out there for data management, is there a work around for this problem?
I may not fully understand your question, but as an example of general use, I would typically convert the matrices to dataframes and then do something like this:
combi <- rbind(dataframe1, dataframe2)
If you know they are matrices, you can do this with multidimensional arrays:
X <- matrix(1:100, 10,10)
s1 <- X[seq(1, 9,2), ]
s2 <- X[seq(2,10,2), ]
XX <- array(NA, dim=c(2,5,10) )
XX[1, ,] <- s1 #Note two commas, as it's a 3D array
XX[2, ,] <- s2
dim(XX) <- c(10,10)
XX
This will copy each element of s1 and s2 into the appropriate slice of the array, then drop the extra dimension. There's a decent chance that rbind is actually faster, but this way you won't need to re-sort it.
Caveat: you need equal sized splits for this approach.
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
I have three different matrices:
m1, which has 12 rows and 5 columns;
m2, which has 12 rows and 4 columns; and
m3, which has 12 rows and 1 column.
I'm trying to build a series of 3-column matrices (p1 to p20) from this, such that in each p matrix:
p[,1] is taken from m1,
p[,2] is taken from m2, and
p[,3] is taken from m3.
I want the process to be exhaustive, so that I create all 20 possible 3-column matrices, so sampling m1, m2, and m3 (a solution I already tried) doesn't seem to work.
I tried half a dozen different for loops, but none of them accomplished what I wanted, and I played with some permutation functions, but couldn't figure out how to make them work in this context.
Ultimately, I'm trying to do this for an unknown number of input matrices, and since I'm still new to R, I have no other ideas about where to start. Any help the forum can offer will be appreciated.
## Example matrices
m1 <- matrix(1:4, nrow=2)
m2 <- matrix(1:6, nrow=2)
m3 <- matrix(1:2, nrow=2)
## A function that should do what you're after
f <- function(...) {
mm <- list(...)
ii <- expand.grid(lapply(mm, function(X) seq_len(ncol(X))))
lapply(seq_len(nrow(ii)), function(Z) {
mapply(FUN=function(X, Y) X[,Y], mm, ii[Z,])
})
}
## Try it out
f(m1)
f(m1,m2)
f(m1,m2,m3)
It looks like your problem can be split into two parts:
Create all valid combination of indexes from 1:5, 1:4 and 1
Compute the matrices
For the first problem, consider a merge without common columns (also called a "cross join"):
merge(data.frame(a=1:5), data.frame(a=1:4), by=c())
Use a loop to construct a data frame as big as you need. EDIT: Or just use expand.grid, as suggested by Josh.
For the second problem, the alply function from the plyr package will be useful. It allows processing a matrix/data frame row by row and collects the results in a list (a list of matrices in your case):
alply(combinations, 1, function(x) { ... })
combinations is the data frame generated by expand.grid or the like. The function will be called once for each combination of indexes, x will contain a data frame with one row. The return values of that function will be collected into a list.