R populate multidimensional array - arrays

Hi I am stuck with one of these simple but time-consuming errors:
How can I populate an array with loops? I know I am on a C approach here
and R isn't C.
Data <-[SOMETHING HERE]
One <-200
Two <-100
array222 <- array(0,length(SomeLength))
for (i in 1:One)
{
for (j in 1:Two)
{
array222[i][j] = sample(Data,1)
}
I want to populate the array with random samples from another dataset but all
I get is this:
Warning in array222[i][j] = sample(Data, 1) :
number of items to replace is not a multiple of replacement length

First of all, you wouldn't use loops to do this in R. You'd just do
array222 <- matrix(sample(Data, One*Two, replace=T), nrow=One, ncol=Two)
But going back to your code, you fail to properly initialize your array222 variable. The matrix() syntax is probably easier for a 2-D array, but you could also use array(0, dim=c(One,Two)). You need to create it with the proper dimensions.
And additionally, the proper way to index a dimensional array is
array222[i,j] #NOT array222[i][j]

Related

Create 2-D array of strings with nested fill

I am initializing a vector of strings like this
mask = fill(fill(' ', maxx), maxy)
in order to then populate it by setting individual elements:
mask[y][x] = '·'
This doesn't work: I get maxy times the same string. I guess the outer fill just creates a list of pointers to the Vector created by the inner fill (the documentation of fill! confirms this explicitly). What should I do instead?
One solution is to use a list comprehension like this:
mask = [fill(' ', maxx) for y in 1:maxy]
(But I'd still be interested to learn whether there is a solution with fill.)

How do I create a string of array combinations given a list of "source code" strings?

Basically, I’m given a list of strings such as:
["structA.structB.myArr[6].myVar",
"structB.myArr1[4].myArr2[2].myVar",
"structC.myArr1[3][4].myVar",
"structA.myArr1[4]",
"structA.myVar"]
These strings are describing variables/arrays from multiple structs. The integers in the arrays describe the size each array. Given a string has a/multiple arrays (1d or 2d), I want to generate a list of strings which go through each index combination in the array for that string. I thought of using for loops but issue is I don’t know how many arrays are in a given string before running the script. So I couldn’t do something like
for i in range (0, idx1):
for j in range (0, idx2):
for k in range (0, idx3):
arr.append(“structA.myArr1[%i][%i].myArr[%i]” %(idx1,idx2,idx3))
but the issue is that I don’t know how I can create multiple/dynamic for loops based on how many indexes and how I could create a dynamic append statement that changes per each string from the original list since each string will have a different number of indexes and the arrays will be in different locations of the string.
I was able to write a regex to find all the index for each string in my list of strings:
indexArr = re.findall('\[(.*?)\]', myString)
//after looping, indexArr = [['6'],['4','2'],['3','4'],['4']]
however I'm really stuck on how to achieve the "dynamic for loops" or use recursion for this. I want to get my ending list of strings to look like:
[
["structA.structB.myArr[0].myVar",
"structA.structB.myArr[1].myVar",
...
"structA.structB.myArr[5].myVar”],
[“structB.myArr1[0].myArr2[0].myVar",
"structB.myArr1[0].myArr2[1].myVar",
"structB.myArr1[1].myArr2[0].myVar",
…
"structB.myArr1[3].myArr2[1].myVar”],
[“structC.myArr1[0][0].myVar",
"structC.myArr1[0][1].myVar",
…
"structC.myArr1[2][3].myVar”],
[“structA.myArr1[0]”,
…
"structA.myArr1[3]”],
[“structA.myVar”] //this will only contain 1 string since there were no arrays
]
I am really stuck on this, any help is appreciated. Thank you so much.
The key is to use itertools.product to generate all possible combinations of a set of ranges and substitute them as array indices of an appropriately constructed string template.
import itertools
import re
def expand(code):
p = re.compile('\[(.*?)\]')
ranges = [range(int(s)) for s in p.findall(code)]
template = p.sub("[{}]", code)
result = [template.format(*s) for s in itertools.product(*ranges)]
return result
The result of expand("structA.structB.myArr[6].myVar") is
['structA.structB.myArr[0].myVar',
'structA.structB.myArr[1].myVar',
'structA.structB.myArr[2].myVar',
'structA.structB.myArr[3].myVar',
'structA.structB.myArr[4].myVar',
'structA.structB.myArr[5].myVar']
and expand("structB.myArr1[4].myArr2[2].myVar") is
['structB.myArr1[0].myArr2[0].myVar',
'structB.myArr1[0].myArr2[1].myVar',
'structB.myArr1[1].myArr2[0].myVar',
'structB.myArr1[1].myArr2[1].myVar',
'structB.myArr1[2].myArr2[0].myVar',
'structB.myArr1[2].myArr2[1].myVar',
'structB.myArr1[3].myArr2[0].myVar',
'structB.myArr1[3].myArr2[1].myVar']
and the corner case expand("structA.myVar") naturally works to produce
['structA.myVar']

Making an array out of big number of matrices in r

I'm trying to work with arrays, but I can't seem to make one that works for my data. I have 14 matrices I would like to put in an array, but I can't figure out the way to do it without manually writing c(m1,m2,m3...) to put in all of them
this is what i tried:
m_list <- mget(paste0("well_", 0:13)) ###to make a list of all my matrices
a <- array(c(m_list),
dim = c(7338, 15, 14))
but when I try to look at the array I created something is not right with it cause I try to call for one value, like this:
print(a[1,4,2])
but I get entire columns.
I assume the error is in the list of matrices. Please help
An answer to your question is that you should use do.call(c, m_list) instead of c(m_list). (Take a couple of small matrices and try to see what c(m_list) and c(m1, m2) return.)
Also you might want to think some more whether working with an array is better than working with a list and, more importantly, how you could avoid having multiple matrices in the first place and instead to directly read/define them as a list or an array.
You can simply use unlist inside your array function call instead of c.
a = array(unlist(m_list), dim = c(dim(m_list[[1]]), length(m_list)))
Some reproducible data:
m1 = matrix(1:5, 5, 5)
m2 = matrix(5:1, 5, 5)
m_list = list(m1, m2)

How to divide cell array into array and vector

This is my first time posting so i hope you can help me. I am trying to write a function in matlab.
I have laded data from a file into a cell array. First column contains statements and the second contains T for true og F for false. I now want to split this array into a cell array with the statements and a logical vector with 1 for True and -1 for false.
I use the fgetl within a loop to read all the lines into the cellarray
Try to write it a bit more neatly next time, and consider including a small example.
Here is what you seem to be looking for:
Suppose you have a matrix M and want to split that into M_true and M_false
M = {1,'T';
22,'F';
333,'T'}
idx_T=strcmp(M(:,2),'T')
M_true = M(idx_T,1)
M_false = M(~idx_T,1)

Store array while executing for loop

I have a function which is executed 200 times like this
for (l in 1:200) {
fun.ction(paramter1=g, paramter2=h)$element->u[z,,]
}
u is an array:
u<-array(NA, dim=c(2000,150,7))
of which I know it should have the right format. The element of func.tion is also an array which has the same dimensions. Hence, is there some way to fill the array u in each of the 200 runs with the array resulting from fun.ction()$element? I tried to use indexing via a list (u[[z]]). It saves the array but as a list so that I can't access the elements afterwards which I would need to. I appreciate any help.
I am not sure what it is that you want, but if you just want to store 200 arrays of dimensions (2000,150,7) you can just make another array with a fourth dimension of 200.
storage.array <- array(dim=c(2000,150,7, 200))
And then store your (2000, 150, 7) arrays in the fourth dimension:
for (i in 1:200){
storage.array[,,,i] <-
fun.ction(paramter1=g, paramter2=h)$element}
Then you can access each of the ith array by:
storage.array[,,,i]
But I guess that will be too big an array for R to handle, at least it is in my computer.
An example that you can easily reproduce with smaller arrays:
storage.array <- array(dim=c(20,2,7, 200))
fun.ction <- function(parameter1, parameter2){
array(rnorm(140, parameter1, parameter2), dim=c(20,2,7))
}
for (i in 1:200){
storage.array[,,,i]<- fun.ction(10, 10)
}
But as Roland and Thomas have said, you should make your code reproducible and define correctly what you want, so it is easier to answer without trying to guess what your problem is.
Best regards

Resources