Home > front end >  Calculate function values and save to array in R
Calculate function values and save to array in R

Time:02-27

For example x^2 from 1 to 10.

In more pleasant to use languages like C# or Java its trivial task, I can't even find solution on google for R.

Basically I need equivalent of this:

public double[] Func(){
   int[] arr = new int[10];
   for (int i = 0; i <= 9; i  ) {
      arr[i] = Math.Pow(i 1, 2);
   }
   return arr;
} 

Edit

For now I have this but it doesn't do anything:

seq <- 1:10
res <- vector()
for (x in seq) {append(res,x^2)}

Edit Solved

seq <- 1:100
res <- vector()
for(x in seq) { res<-append(res, x^2) }

This way works no matter the function you want to use.

CodePudding user response:

In the comments you said that x^2 was just a simple example, you wanted it to work more generally for other functions. In that case, there are two possibilities:

For functions like x^2 that are vectorized, just do the calculation:

seq <- 1:10
res <- seq^2

Most simple functions in R are vectorized, so this is the most common case, but there are also lots of functions where f(x) expects x to be a single value, not a vector. For those, there are lots of choices:

seq <- 1:10

# 1. Turn f into a vectorized function:

f2 <- Vectorize(f)  
res <- f2(seq)

# 2.  Use one of the many `*apply` functions:

res <- sapply(seq, f)

# 3.  Use a loop, like in other languages that lack vectorized operations:

res <- numeric( length(seq) )
for (i in seq_along(seq))
  res[i] <- f(seq[i])

People mostly avoid using for loops in R, because they tend to lead to slower code. But sometimes they are best, in situations where things aren't as simple as this.

  •  Tags:  
  • r
  • Related