cmartini86
cmartini86

Reputation: 1

Performing Calculations Across Columns More Efficiently (R Studio)

I'm using R 4.1.0

Let's say I have a data frame called my_df and it looks like this:

ID x
A 24
B 108
C 76

and I want to calculate each value of column x as such:

(x/180) * 100

and place the result in a new column so it will look like this:

ID x y
A 24 13.33
B 108 60
C 76 42.22

What I have tried is a for loop:

for (i in 1: length(my_df) {
   my_df$y[i] <- (my_df$x[i]/180) * 100
}

The above code works. However, the actual data frame I'm working with is over a million rows long. When I run that for loop for my data frame, it takes a really long time to execute.

So, my question is: is there a way to execute the above in a more efficient way?

Thanks in advance.

Upvotes: 0

Views: 121

Answers (1)

akrun
akrun

Reputation: 887501

We don't need a loop as arithmetic operations are vectorized (should be much faster than looping)

my_df$y <- 100 *(my_df$x/180)

Upvotes: 1

Related Questions