Coding numerical derivatives in R - r

I am totally new to R and I am struggling to write a code to find the numerical derivatives of vector fields. I have two matrices U and V, e.g.,
U <- matrix(runif(9), nrow = 3, ncol = 3, byrow = T)
V <- matrix(runif(9), nrow = 3, ncol = 3, byrow = T)
These matrices (not actual values obviously) represents the components of a 2D wind vector field. I would like to code the numerical derivatives of the 2 vector components du/dy and dv/dx. I have no idea how to do this in R. Please help. Sorry in advance if this question has been answered already.

What you are looking for is the diff() function. You can apply it efficiently over a dimension of a matrix using an apply
U <- matrix(runif(9), nrow = 3, ncol = 3, byrow = T) #Your wind component
apply(U,2,diff) #change the '1' by '2' to apply diff over the other dim
Hope this helped.

Related

Converting MATlab Loop to R - Cell Structures

I am having trouble to convert a Matlab loop into R.
For every {t,tau}, calculate the o indexed with a value that refers to the value of [t,tau]
from within the loop. In the matlab code it is done via a cell structure that applies from outside the loop.
o{1,1} = [1 0]';
o{1,2} = [0 0]';
o{2,1} = [1 0]';
o{2,2} = [0 1]';
Within the loop something like this is calculated:
nat_log(A'*o{t,tau})
How can I manage the loop to use the values of t and tau that I set within the loop in order to adress certain "o" within a list?
First my attempt:
Timesteps = 2 # total timesteps/iterations
Tau = 2 # amounts of observations o within 1 timestep; at t=1 and tau-1 = o = [0 0], above denoted {1,2}
for(t in 1:length(Timesteps)){
qs[,t] = matrix(c(.5,.5)) # This is the posterior distribution to be updated,
for (t in 1:length(Timesteps)){ # but that's not that important
for (tau in 1:length(Timesteps)){
****some more math****
y = x * o[[t,tau]] # THIS is the important part!
etc. .... ..... .... ....
I tried something like
o<- vector("list", length = 2 * 2)
dim(o) <- matrix(c(2, 2))
o[[1,1]] <- matrix(c(1, 0), nrow = 2, ncol =1, byrow = TRUE)
o[[1,2]] <- matrix(c(0, 0), nrow = 2, ncol =1, byrow = TRUE)
o[[2,1]] <- matrix(c(1, 0), nrow = 2, ncol =1, byrow = TRUE)
o[[2,2]] <- matrix(c(0, 1), nrow = 2, ncol =1, byrow = TRUE)
The orginial matlab code that I am trying to reproduce can be found here:
https://github.com/rssmith33/Active-Inference-Tutorial-Scripts/blob/main/Pencil_and_paper_exercise_solutions.m
Line: 46-103 (it is essentially Bayes inference with Markov property...)
If someone has an idea, I would be very thankful. I am just a med student interested in math and would love to see this available for R as well.

how to create a matrix from sub-elements of a list?( in R)

to put it simply, I have a list of DFMs created by quanteda package(LD1). each DFM has different texts of different lengths.
now, I want to calculate and compare lexical diversity for each text within DFMs and among DFMs.
lex.div <-lapply(LD1, function(x) {textstat_lexdiv(x,measure = "all")})
this leaves me with a list of S3 type data, and within each of which, there are different attributes that are lexical diversity measures.
lex.div[[1]]$TTR
[1] 0.2940000 0.2285000 0.2110000 0.1912500 0.1802000 0.1671667 0.1531429 0.1483750 0.1392222
[10] 0.1269000
lex.div[[2]]$TTR
[1] 0.3840000 0.2895000 0.2273333 0.2047500 0.1922000 0.1808333 0.1677143 0.1616250 0.1530000
[10] 0.1439000 0.1352727 0.1279167 0.1197692 0.1125000 0.1069333
here comes the problem. I need all the TTR values in one matrix. i want lex.div[[1]]$TTR to be the first row of the matrix, lex.div[[2]]$TTR to be the second, and so on. note that the length of lex.div[[1]]$TTR ≠ lex.div[[2]]$TTR.
here is what I've done so far:
m1 <-matrix(lex.div[[1]]$TTR, nrow = 1, ncol = length(lex.div[[1]]$TTR))
m.sup <- if(ncol(m1) < 30) {mat.to.add = matrix(NA, nrow = nrow(m1), ncol = 30 - ncol(m1))}
m1 <-cbind(m1, m.sup)
m2 <-matrix(lex.div[[2]]$TTR, nrow = 1, ncol = length(lex.div[[2]]$TTR))
m.sup <- if(ncol(m2) < 30) {mat.to.add = matrix(NA, nrow = nrow(m2), ncol = 30 - ncol(m2))}
m2 <-cbind(m2, m.sup)
m3 <-matrix(lex.div[[3]]$TTR, nrow = 1, ncol = length(lex.div[[3]]$TTR))
m.sup <- if(ncol(m3) < 30) {mat.to.add = matrix(NA, nrow = nrow(m3), ncol = 30 - ncol(m3))}
m3 <-cbind(m3, m.sup)
...
m.total <-rbind (m1,m2,m3...)
but I cannot do it this way. can you help me write a for loop or sth to get it done easier and quicker?
You can try the code below
TTRs <- lapply(lex.div, `[[`, "TTR")
m <- t(sapply(TTRs, `length<-`, max(lengths(TTRs))))

How to create a 3D array from 2D matrices in R?

I would like to create a 3D array based on a couple of 2D matrices in R, but I have no idea. Let's say we have the following three matrices:
matrix1 <- matrix(1:1, nrow = 5, ncol = 5)
matrix2 <- matrix(2:2, nrow = 5, ncol = 5)
matrix3 <- matrix(3:3, nrow = 5, ncol = 5)
I would like to know how to create one [1:3, 1:5, 1:5] array, as a combination of the three matrices. Thank you!
We can concatenate the matrixes together into a vector, use array to construct a 3D array with specified dim
ar1 <- array(c(matrix1, matrix2, matrix3), c(5, 5, 3))

Remove columns with lowest variance

I have a large matrix of low values, such as:
m <- matrix(c(0.000000217, 0.000000021, 0.000000403, 0.000000272,
0.000000209, 0.000000310, 0.000000161, 0.000000243,
0.000000375, 0.000000185, 0.000000298, 0.000000269),
nrow = 3, ncol = 4)
In what I'm working on, columns with low variance are causing issues. My actual matrix has over 7,000 rows. How can I remove the bottom n columns of variance? I've tried various iterations of apply() with no success.
m <- matrix(c(0.000000217, 0.000000021, 0.000000403, 0.000000272,
0.000000209, 0.000000310, 0.000000161, 0.000000243,
0.000000375, 0.000000185, 0.000000298, 0.000000269),
nrow = 3, ncol = 4)
Use apply and var to get column variances, and order and head to get the top or bottom n.
m[, head(order(apply(m, 2, var), decreasing = TRUE), -n)]
using %in% and which.min
m[,c(1:length(m[1,]))[!(c(1:length(m[1,])) %in% which.min(apply(m, 2, var)))]]

replicate by columns, but transposing in r with vectorization

I have a matrix like this:
m1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, byrow = TRUE)
and I would like to have every column repeated "m" times, but transposing into files and concat the results horizontally. I mean, suppose "m" is 3, I would like to have something like this:
matrix(c(1,4,7,2,5,8,3,6,9,1,4,7,2,5,8,3,6,9,1,4,7,2,5,8,3,6,9),
nrow = 3, byrow = TRUE)
Is there any vectorized way to do this?
I have tried using rep to replicate the columns and then transposing, but I end with many rows
We can use rep
matrix(rep(m1, each=nrow(m1)), nrow=3)
Or
`dim<-`(rep(m1, each=nrow(m1)), dim(m1)*c(1,3))
Or
t(replicate(nrow(m1), c(m1)))
data
m1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, byrow = TRUE)

Resources