steadyfish
steadyfish

Reputation: 877

R: Assignment to match dimensions of target array

Consider following snippet of code -

targetArray = array(Inf, dim=c(3,5))
targetArray
     [,1] [,2] [,3] [,4] [,5]
[1,]  Inf  Inf  Inf  Inf  Inf
[2,]  Inf  Inf  Inf  Inf  Inf
[3,]  Inf  Inf  Inf  Inf  Inf

temp = NA
data = rnorm(n = 15, mean = 2, sd = 2)

Now, if I assign data or temp to targetArray, it will alter the dimensions of targetArray. Is there any way to make sure that it doesn't happen?

targetArray = temp
targetArray
[1] NA

targetArray = data
targetArray
 [1]  2.4026814  2.4011577 -0.5089512  1.6223969  4.7533560  0.6619385 -0.5676509  1.3093745  1.2342189 -0.5368143  4.4641850  1.9515940  2.0025938 -1.1589229
[15]  1.6669973

How do I make sure that the assignment matches dimensions of targetArray? i.e. when I enter targetArray = temp, it should change all the elements of targetArray to NA without changing its dimensions. Similarly, for targetArray = data, it should realign 1 x 15 dimensional data vector to conform to dimensions of targetArray and assign it (either rowwise or columnwise).

Upvotes: 0

Views: 190

Answers (1)

eddi
eddi

Reputation: 49448

I think your expectations are a bit off. That assignment doesn't care what's on the LHS - you're not "filling-in" data into targetArray, but rather (usually copying and) assigning some data the name targetArray.

To get the result you want, just adjust the dimensions of the input data, e.g.

targetArray = matrix(data, ncol = ncol(targetArray), nrow = nrow(targetArray))

Upvotes: 1

Related Questions