product of first n elements of vector - r

I have problem to find first n elements of vector in R.
I have tried prod() function, but question is how first n elements?
How to find product of first n elements of vector in R?

An idea would be to create a function where you determine vector entry and length of desired elements for product formula
# Function
prodFun <- function(x, len){
return(prod(x[1:len]))
}
# Example
x <- 1:10
prodFun(x, 5)

Related

How to do a cumulative sum inverse square weighting based upon how many items you want to calculate off a vector in R?

Suppose I have a vector of length 10
vec <- c(10,9,8,7,6,5,4,3,2,1)
and I wanted to create a function that takes in a subset length value (say 3) and computes the squared inverse up to that length. I would like to compute:
10+(9/(2^2))+(8/(3^2))
which would be
vec[1]+(vec[2]/(2^2))+(vec[3]/(3^2))
but with a function that can take input of the subset length.
The only solution I can think of is a for loop, is there a faster more elegant solution in R?
Yes, you can use the fact that most operations in R are vectorised to do this without a loop:
vec <- c(10,9,8,7,6,5,4,3,2,1)
cum_inverse_square <- function(vec, n) {
sum(vec[1:n] / (1:n)^2)
}
cum_inverse_square(vec, 3) == 10+(9/(2^2))+(8/(3^2)) # TRUE

Faster method of counting specified values from rows in large matrix in R

MC is a very large matrix, 1E6 rows (or more) and 500 columns. I am trying to get the number of occurrences of the values 1 through 13 for each of the columns. Sometimes the number of occurrences for one of these values will be zero. I would like my final output to be a 300X13 matrix (or data frame) with these count values. I am wondering if anyone can suggest a more efficient manner then what I currently have, which is the following:
MCct<-matrix(0,500,13)
for (j in 1:500){
for (i in 1:13){
MCct[j,i]<-length(which(MC[,j]==i))}}
I don't that table works, because I need to also know if zero occurrences occurred...I couldn't figure it out how to do that if it is possible. And I am only somewhat familiar with apply, so maybe there is a method to use that...I haven't been successful in figuring that out yet.
Thanks for the help,
Vivien
You could do this with sapply (to iterate from 1 to 13) and colSums (to add up the columns of j):
MCct <- sapply(1:13, function(i) {
colSums(MC == i)
})
Suppose you have a set of values you're interested in
set <- 1:4
n = length(set)
and you have a matrix that includes those values, and others
m <- matrix(sample(10, 120, TRUE), 12, 10)
Create a vector indicating the index in the set of each matching value
idx <- match(m, set)
then make the index unique to each column
idx <- idx + (col(m) - 1) * n
idx ranges from 1 (occurrences of the first set element in the first column) to n * ncol(m) (occurrence of the nth set element in the last column of m). Tabulate the unique values of idx
v <- tabulate(idx, nbin = n * ncol(m))
The first n elements of v summarize the number of times set elements 1..n appear in the first column of m. The second n elements of v summarize the number of times set elements 1..n appear in the second column of m, etc. Reshape as the desired matrix, where each row represents the corresponding member of the set.
matrix(v, ncol=ncol(m))
table can count zero occurrences, you just need to create a factor that has the whole range of levels, e.g.
apply(MC, 2, function(x) table(factor(x, levels=1:13)))
This is not as efficient as #Patronus' solution though.

R sum element X in list of vector

I just started doing some R script and I can't figure out this problem.
I got a list of vector let say
myListOfVector <- list(
c(1,2),
c(1,2),
c(1,2),
c(1,2)
)
what I want is the sum of each X element of each vector that are in my list base on the position of the element
so that if I have 3 vector that contains (a, b, c), I will get the sum of each a, each b and each c in a list or vector
I know that each vector are the same length
What I seek is something like that
result <- sum(myListOfVector)
# result must be c(4, 8)
Does anybody have an idea ?
The only way I've been able to do it is by using a loop but it take so much time that I can't resign to do it.
I tried some apply and lapply but they don't seem to work like I want it to because all I have is one vector at a time.
Precision :
The list of vector is returned by a function that I can't modify
I need an efficient solution if possible
A list of vectors of the same length can be summed with Reduce:
Reduce(`+`, myListOfVector)
Putting it in a matrix and using colSums or rowSums, as mentioned by #AnandaMahto and #JanLuba, might be faster in some cases; I'm not sure.
Side note. The example in the OP is not a list; instead, it should be constructed like
myListOfVector <- list( # ... changing c to list on this line
c(1,2),
c(1,2),
c(1,2),
c(1,2)
)
you should first convert your list to a matrix:
mymatrix=matrix(myListOfVector,ncol=2,byrow=T)
and then use colSums:
colSums(mymatrix)

Matrix multiplication using variable element producing Error non-conformable arguments

I am a newbie to R, but avid to learn.
I have been trying endlessly to create a matrix with a variable element (in this case [2,2]). The variable element should take number 4 on the first run and 5 on the second (numbers).
This matrix would be multiplied by another matrix (N0) and produce a result matrix (resul).
Up so far, I have only been able to create the initial matrix with the variable element using a for loop, but I am having problems indexing the result matrix. I have tried several versions, but this is the latest. Any suggestions would be greatly appreciated. Thank you.
numbers <- c(4,5,length.out = 2)
A <- matrix(c(1,2,3,NA),nrow=2,ncol=2)
resul <- matrix(nrow=2,ncol=1)
for (i in 1:2) {
A[2,2]<- matrix(numbers[i])
N0 <- matrix(c(1,2),nrow=2,ncol=1)
resul[i,]<- A[i,i]%*%N0
}
Your code has two distinct problems. the first is that A[i,i] is a 1 x 1
matrix, so you're getting an error because your multiplying a 1 x 1 matrix
by a 2 x 1 matrix (N0).
you could either drop the subscript [i,i] and initialize the result to be
a two by two matrix like so:
result <- matrix(nrow=2,ncol=1)
for (i in 1:2){
A[2,2]<- matrix(numbers[i])
# a colunm vector
N0 <- matrix(c(1,2),
nrow=2,
ncol=1)
# note the index is on the column b/c `A%*%N0` is a column matrix
result[,i]<- A%*%N0
}
or you could either drop the the second subscript [i,] and initialize the result to be
a two by two matrix like so:
result <- matrix(nrow=2,ncol=1)
for (i in 1:2){
A[2,2]<- matrix(numbers[i])
# a colunm vector
N0 <- matrix(c(1,2),
nrow=2,
ncol=1)
result[i,]<- A[i,]%*%N0
}
but it's not clear from you post which (if either) answer is the correct one. Indexing is tricky :)

Compute the minimum of a pair of vectors

If I have a vector c(1,2,3) and another vector of the same length c(1,4,1) . Is there some way to find the minimum of each pair of numbers in the list pair? i.e. have a function that returns c(1,2,1)` I don't want to use any apply function or loops because my vectors will be very big and looping through them would take a long time.
You want pmin():
> x <- c(1,2,3)
> y <- c(1,4,1)
> pmin(x,y)
[1] 1 2 1

Resources