Putting each value in a table - r

I have an r code where I am printing the values and doing a small calculation on it.
for (j in sample.data1$SENTIMENT_STRENGTH_91D) {
i = (j - max(sample.data1$SENTIMENT_STRENGTH_91D))/C
}
this prints out each value of i. How can I put these values into a vector inside the loop?
I have tried this code but it only gives the last values
for (j in sample.data1$SENTIMENT_STRENGTH_91D) {
i = (j - max(sample.data1$SENTIMENT_STRENGTH_91D))/C
D <- c(i)
}

You can change your for loop to the following:
D = numeric(0)
for (j in sample.data1$SENTIMENT_STRENGTH_91D) {
i = (j - max(sample.data1$SENTIMENT_STRENGTH_91D))/C
D <- c(D, i)
}
But it turns out growing an object in a for loop in R is very slow. You probably don't even need a for loop. You can try taking advantage of R's vectorization:
x <- sample.data1$SENTIMENT_STRENGTH_91D
D <- (x - max(x))/C

Related

How do I populate a 10x10 matrix in R with values 1-100 using two for loops?

How do I populate a 10X10 empty matrix called mat.horiz, with values 1 to 100 by row (i.e. filling in values across columns, in descending rows), using two for() loops?
New to loops and am barely grasping the structure of them. Any help and explanation would be much appreciated:)
If you really want to use for loops, you can try the code below
out <- matrix(NA,10,10)
for (i in 1:10) {
for (j in 1:10) {
out[i,j] <- j + (i-1)*10
}
}
or
out <- matrix(NA,10,10)
k <- 0
for (i in 1:10) {
for (j in 1:10) {
k <- k + 1
out[i,j] <- k
}
}
A simpler way is using
out <- matrix(1:100,10,10,byrow = TRUE)

why my sum() function don't work for the matrix operations in R

The following is my R code, I want the tx[1, 1] = 1*2^1 + 4*5^2 + 7*8^3, tx[1, 2] = 4*5 + 7*8^2, tx[1, 3] = 7*8,but it only including 7*8^3 for tx[1, 1] and 7*8^2 for tx[1, 2]. The other elements in the tx matrix only include the last term in the sum operation too. So,could anyone tell me how to rectify my code to have a correct output? Thanks in advance!
A <- matrix(c(1:9),ncol=3)
B <- matrix(c(2:10),ncol=3)
tx<-matrix(rep(NA,3*3),3,3)
for(j in 1:3)
{
for(i in 1:3)
{
for(k in 1:3-i+1)
{
tx[j,i]<-sum(A[j,k+i-1]*(B[j,k+i-1])^k)
}
}
}
Right now it's not summing the results of each loop, just saving out whatever the last loop result happens to be. Try this instead:
A <- matrix(c(1:9),ncol=3)
B <- matrix(c(2:10),ncol=3)
tx<-matrix(rep(0,3*3),3,3)
for(j in 1:3)
{
for(i in 1:3)
{
for(k in 1:3-i+1)
{
tx[j,i]<-tx[j,i] + (A[j,k+i-1]*(B[j,k+i-1])^k)
}
}
}
I initialized the tx matrix to start at 0 and added the result of each loop to the existing total, so that it increments over each loop.

R: How could I change this loop to apply?

I'm currently working on an R program, where there is one part of this program that computes in a loop two values which are interdependant. Although since I have to do 100,000 iterations it takes so long time.
So I would like to substitute this for loop for an apply loop or some more efficient function, but I don't know how to do it. Could someone help me?
p <- c()
for(i in 1:n) {
if(i == 1) {
x <- b[i]
}
else {
x <- c(x, max(h[i - 1], p[i]))
}
h <- c(h, x[i] + y[i])
}
Thank you very much!!
You don't seem to have a full working example here, but the main problem is that building up the x and h vectors with the c() function is very slow. It's better to preallocate them:
x <- numeric(n) # allocate vector of size n
h <- numeric(n)
and then fill them in as you go by assigning to x[i] and h[i]. For example, the following loop:
x <- c(); for (i in 1:100000) x <- c(x,1)
takes about 10 seconds to run on my laptop, but this version:
x <- numeric(100000); for (i in 1:100000) x[i] <- 1
does the same thing while running almost instantly.

For loop function with two subscripts

I am new to writing loop functions and I am trying to solve this. I would like the y matrix to be populated with the values obtained from the for loop. Unfortunately y remains blank and full of 0's after the loop is executed.
mv <- c(0,1,2) # location vector
s <- 1 # scale
increment <- seq(-6,6,0.01) # Create a sequence of x values
y=matrix(0,length(increment),length(mv))
for (i in length(increment)) {
for (j in length(mv)) {
y[i,j] <- 1/(1+ exp(-(increment[i]-mv[j])/s))
}
}
Change your loop to start at 1, for now it is only using 1 value (length(increment)):
for (i in 1:length(increment)) {
for (j in 1:length(mv)) {
y[i,j] <- 1/(1+ exp(-(increment[i]-mv[j])/s))
}
}

subscript out of bounds error with two for loops inside the function

I am trying to use a two dimension matrix to produce a two dimension matrix result where
the number of rows and number of columns are determined in a new way everytime I change the values in the function which determines the number of rows and number of columns accordingly.
The function that I would like to ask and resolve the "subscript out of bounds" problem is the following:
HRC <- function(n,b,c)
{
R=matrix( ,nrow = n*b, ncol = c)
R[0,]=133
for (j in 1:c)
{
r=rnorm(n*b)
for (i in 1:n*b){
R[i+1,j]=R[i,j]+3*b/r[i]
}
}
return(R)
}
HRC(10,1,3)
The error message that I get is the following:
Error in R[i + 1, j] = R[i, j] + 3 * b/r[i] : subscript out of bounds
I wonder how I can resolve this problem. Thank you so much in advance.
R's indexing starts at 1, not 0.
You also have to be careful with the operators precedence rules: the : operator has higher precedence than *. See ?Syntax.
This should work:
HRC <- function(n, b, c) {
R <- matrix(NA, nrow = n*b, ncol = c)
R[1,]=133
for (j in 1:c) {
r = rnorm(n*b)
for (i in 1:(n*b-1)){
R[i+1,j] = R[i,j] + 3*b/r[i]
}
}
return(R)
}
HRC(10,1,3)
The problem is that you loop from row b to row n*b (with stride b, due to the precedence of * and :) and then index to one greater, so you attempt to index row n*b + 1 of R, which is out of bounds.
R[0,]<- will cause incorrect results but not elicit an error from R.
I find the code easier to read if you loop from 2 to n*b, the number of rows, and write the formula in terms of creating row i from row i-1 (rather than creating row i+1 from row i).
In addition, you can drop one loop dimension by vectorizing the operations over the rows:
HRC <- function(n, b, c) {
R <- matrix(NA, nrow = n*b, ncol = c)
R[1,] <- 133
r <- matrix(rnorm(n*b*c), ncol=c)
for (i in 2:(n*b)){
R[i,] <- R[i-1,] + 3*b/r[i-1,]
}
return(R)
}
HRC(10,1,3)
Here, the same number of random samples are taken with rnorm but they are formed as a matrix, and used in the same order as used in the question. Note that not all of the random values are actually used in the computation.
If you set a random seed and then run this function, and the function in #flodel's answer, you will get identical results. His answer is also correct.
I think you are making three mistakes:
First: You are messing up the row count on the index. It should be 1:(n*b) and not 1:n*b.
Second: In R, indexing starts at 1. So R[0,] should be replaced by R[1,].
Third: You are running the loops in the right bounds 1:c and 1:(n:b), but you are probably not keeping track of the indices.
Try this:
set.seed(100)
HRC <- function(n, b, c) {
R <- matrix(0, nrow = n*b, ncol = c)
R[1,] <- 133
for (j in 1:c) {
r <- rnorm(n*b)
for (i in 2:(n*b)){
R[i,j] <- R[i-1,j] + 3*b/r[i-1]
}
}
return(R)
}
HRC(10,1,3)
Lastly, I would like to warn you about interchangeable use of the assignment operators. See here.

Resources