Multiplication of a number with a table - r

I have inserted a table from text in R with the command read.table, but I want to multiply the prices in one of its rows with some number. I have tried to do the following:
x=matrx(, nrow=184,ncol=1)
for (i in 1:184){x[i]=c[2,i+1]*z}
where c is a table of 3 columns and 185 rows and z is a number, say 10. I can not make this multiplication, why is this?
Also, should I insert the tables as matrices or it is the same? If no, is there a way to convert them somehow or insert them with some other command instead of read.table?

In R, a matrix is just a vector of numbers that has dimensions. The matrix function adds the dimensions to the vector. The values in the vector fill each column, in order, in the matrix. Consider:
> x = 5:16
> x
[1] 5 6 7 8 9 10 11 12 13 14 15 16
> xMatrix = matrix(x, nrow = 4)
> xMatrix
[,1] [,2] [,3]
[1,] 5 9 13
[2,] 6 10 14
[3,] 7 11 15
[4,] 8 12 16
Now, values in the vector and the matrix can be accessed using indices:
> x[10:11]
[1] 14 15
> xMatrix[2:3,3]
[1] 14 15
Interestingly, the matrix is still a vector (it's just a vector with dimensions), and can be treated as such:
> xMatrix[10:11]
[1] 14 15
Multiplication in R is vectorized. If you multiply two vectors together, the first value in each vector is multiplied together, the second values in each vector is multiplied together, etc. So:
> x*x
[1] 25 36 49 64 81 100 121 144 169 196 225 256
If one vector is shorter than the other, the short vector is "recycled:"
> x * 1:2
[1] 5 12 7 16 9 20 11 24 13 28 15 32
If you use a single value (a vector of length = 1), then that value is recycled:
> x * 10
[1] 50 60 70 80 90 100 110 120 130 140 150 160
So, putting it all together, you can multiply each value in an entire matrix by a constant simply by using the code:
> xMatrix * 2
[,1] [,2] [,3]
[1,] 10 18 26
[2,] 12 20 28
[3,] 14 22 30
[4,] 16 24 32
If you want to multiply only one row of a vector by a value, and update the contents of the vector, use:
xMatrix[2,] = xMatrix[2,] * 10
to update the second row. Result:
> xMatrix
[,1] [,2] [,3]
[1,] 50 9 13
[2,] 600 100 140
[3,] 70 11 15
[4,] 80 12 16

Related

How to multiply a group of elements within a vector with a matrix, setting all other elements to zero

I'm looking for a way that selects a group of elements within a vector and multiplies this with a matrix, while setting each other element to zero, then repeating this process for the next group.
for example let
a <- c(2:7)
b <- matrix(1:36, byrow = FALSE, nrow = 6)
giving
[[1]]
[1] 2 3 4 5 6 7
[[2]]
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 5 6
[2,] 7 8 9 10 11 12
[3,] 13 14 15 16 17 18
[4,] 19 20 21 22 23 24
[5,] 25 26 27 28 29 30
[6,] 31 32 33 34 35 36
Define a as having three groups:
element 1 and 2 for group 1
element 3 and 4 for group 2
element 5 and 6 for group 3
How can r multiply vector a group 1 with b setting everything else to zero (2 3 0 0 0 0), then repeat with group 2 (0 0 4 5 0 0) and 3 (0 0 0 0 6 7)?
Here's one way to get the result:
k <- 2
v <- rep(1:(length(a) %/% k), each = k)
sapply(unique(v), function(n) a[which(v == n)] %*% b[which(v == n), ])
# [,1] [,2] [,3]
# [1,] 8 32 72
# [2,] 38 86 150
# [3,] 68 140 228
# [4,] 98 194 306
# [5,] 128 248 384
# [6,] 158 302 462
Some explanations. k is the number of elements in each group, in your actual case that should be 56. v is the vector with a corresponding block number at each coordinate. Then I go over all block numbers unique(v), but instead of creating vectors like c(2,3,0,0,0,0) I just take c(2,3) and only the first two rows of the matrix b, which is equivalent to playing with zeros. Also, if the length of a is divisible by k, you may replace the last line with
sapply(unique(v), function(n) a[v == n] %*% b[v == n, ])

How to select the n lowest values, n lowest values excluding the lowest, etc. in a for loop in R?

In R, I want to make a for loop in which I want to select the n lowest values, then the n lowest values excluding lowest value, then the n lowest values excluding the 2 lowest values etc.
Here's an example to clarify:
set.seed(1)
x <- round(rnorm(10,20,15))
n <- 4
I want to get:
7 8 11 15
8 11 15 23
11 15 23 25
15 23 25 27
23 25 27 29
25 27 29 31
27 29 31 44
I tried the following code, but then I do not get the last row (does not include last/highest value). I could get this by adding another code line in the for loop, but was wondering whether this could be done more efficient.
y <- matrix(data=NA, nrow=length(x)+1-n, ncol=n)
for (i in 1:(length(x)-n)) {y[i,] <- sort(x)[i:(i+n-1)]}
Thanks
set.seed(1)
x <- round(rnorm(10,20,15))
n <- 4
Get the pattern:
rbind(sort(x)[1:4], sort(x)[2:5], sort(x)[3:6], sort(x)[4:7], sort(x)[5:8], sort(x)[6:9], sort(x)[6:9], sort(x)[7:10])
Now, use dynamic programming in R to finish (in the general case):
matrix(c( sapply(1:(length(x)+1-n), function(i) sort(x)[i:(i+3)] )),nrow=length(x)+1-n, byrow=TRUE)
[,1] [,2] [,3] [,4]
[1,] 7 8 11 15
[2,] 8 11 15 23
[3,] 11 15 23 25
[4,] 15 23 25 27
[5,] 23 25 27 29
[6,] 25 27 29 31
[7,] 27 29 31 44
The most perfect one:
t(sapply(1:(length(x)+1-n), function(i) sort(x)[i:(i+3)] ))
[,1] [,2] [,3] [,4]
[1,] 7 8 11 15
[2,] 8 11 15 23
[3,] 11 15 23 25
[4,] 15 23 25 27
[5,] 23 25 27 29
[6,] 25 27 29 31
[7,] 27 29 31 44
Note that sapply provides columnwise outputs, hence a transpose finished the inconvinience.
Note to Rob: Apply family (apply, mapply, sapply, tapply etc.) overrides for. Hence, you should use this family as long as possible.

How to read odd rows if column is odd and sum these values in R

I'm trying to calculate the sum column wise of the cells in an 8x8 matrix M[[K]] for when the column is odd it adds the odd rows under it; if the column is even it add the even row cells under it. I then need this to loop through a data folder.
vin <- rep(c(1,0),(NoParticipants/2))
vout <- rep(c(0,1),(NoParticipants/2))
M <- vector("list")
total <- vector("list")
group <- vector("list")
for(k in 1:NoGames){
M[[k]] <- (CumulativeAdjacencyMatrices[[k]][[20]])
total[[k]] <- colSums(M[[k]])
group[[k]] <- (M[[k]]%*%vin)*vin + (NoRounds - (M[[k]]%*%vin))*vout
}
The line with group[[k]] is giving back negative integers (which it shouldn't). How can I re-write the command to do what I want it to? Any thoughts would be greatly appreciated :)
I found where I was wrong. I needed to replace NoRounds with total[[k]] in the last line.
I suggest an alternative to your approach as just traversing through odd and even indexes as follows :
#sample matrix
m <- matrix(sample.int(20, replace = TRUE), nrow = 8, ncol = 8)
> m
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 11 9 2 14 10 11 9 2
[2,] 17 6 9 7 4 17 6 9
[3,] 1 10 20 12 18 1 10 20
[4,] 1 14 8 3 12 1 14 8
[5,] 14 10 11 9 2 14 10 11
[6,] 7 4 17 6 9 7 4 17
[7,] 12 18 1 10 20 12 18 1
[8,] 3 12 1 14 8 3 12 1
#adding odd index columns
> colSums(m[,seq(1,ncol(m),2)])
[1] 66 69 83 83
#adding even index columns
> colSums(m[,seq(2,ncol(m),2)])
[1] 83 75 66 69
# column 1 = sum rows 1,3,5,7 and so on...
for(i in 1:(ncol(m)-2)){
m[,i] <- rowSums(m[,seq(i,8,2)])
}
Hope this helps.

Adding combinations of rows to columns

I have 17 square matrices of order 430 and a large matrix of dimension 92235 x 34
For each square matrix, I wish to add each row's value (from 1 to 430) to a column in the large matrix, taking only those values above the main diagonal. So [1,2][1,3][1,4]..[1,430][2,3][2,4]...[2,430]...[429,430] -- hence, the 92235 row length of the large matrix (A sample of Step 1 is shown here http://imgur.com/4SlUenK)
The square matrix is transposed
Step 1 is repeated but the row values are added to the next column in the large matrix
Repeat Steps 1-3 16 more times until the large matrix is filled
How do I go about doing this?
TIA
EDIT FOR COMMENT
mat = matrix(1:25,5,5)
mat
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
mat2 = cbind(mat[upper.tri(mat)])
mat2
[,1]
[1,] 6
[2,] 11
[3,] 12
[4,] 16
[5,] 17
[6,] 18
[7,] 21
[8,] 22
[9,] 23
[10,] 24
This reads columns then rows. Instead, I would like to read rows then columns so that the result should be:
[,1]
[1,] 6
[2,] 11
[3,] 16
[4,] 21
[5,] 12
[6,] 17
[7,] 22
[8,] 18
[9,] 23
[10,] 24
If you have 17 square matrices ('m1', 'm2',...'m17'), keep them in a list and then use upper.tri to extract the elements above the diagonal and cbind with the elements from the transpose
lst1 <- mget(paste0('m', 1:17))
Out <- do.call(cbind,lapply(lst1, function(x) {x1 <- t(x)
cbind(x[upper.tri(x)], x1[upper.tri(x1)]) }))
dim(Out)
#[1] 92235 34
Here I created the matrices in a list.
Update
Based on the row order of the data,
mat1 <- mat
mat1[lower.tri(mat1, diag=TRUE)] <- NA
as.vector(na.omit(unlist(tapply(mat1, row(mat1), FUN=I))))
#[1] 6 11 16 21 12 17 22 18 23 24
Or as #David Arenburg mentioned in the comments
temp <- t(mat)
temp[lower.tri(temp)]
#[1] 6 11 16 21 12 17 22 18 23 24
You can replace the steps as here in the lapply.
data
set.seed(24)
lst1 <- replicate(17, matrix(sample(1:200, 430*430, replace=TRUE),
430, 430), simplify=FALSE)

How to turn a vector into a matrix in R?

I have a vector with 49 numeric values. I want to have a 7x7 numeric matrix instead.
Is there some sort of convenient automatic conversion statement I can use, or do I have to do 7 separate column assignments of the correct vector subsets to a new matrix? I hope that there is something like the oposite of c(myMatrix), with the option of giving the number of rows and/or columns I want to have, of course.
Just use matrix:
matrix(vec,nrow = 7,ncol = 7)
One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.
A matrix is really just a vector with a dim attribute (for the dimensions). So you can add dimensions to vec using the dim() function and vec will then be a matrix:
vec <- 1:49
dim(vec) <- c(7, 7) ## (rows, cols)
vec
> vec <- 1:49
> dim(vec) <- c(7, 7) ## (rows, cols)
> vec
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 8 15 22 29 36 43
[2,] 2 9 16 23 30 37 44
[3,] 3 10 17 24 31 38 45
[4,] 4 11 18 25 32 39 46
[5,] 5 12 19 26 33 40 47
[6,] 6 13 20 27 34 41 48
[7,] 7 14 21 28 35 42 49

Resources