Eric K
Eric K

Reputation: 15

Two iterations of the same column in R

The goal is to compare the second row with the first row and repeat this. My strategy is to perform two separate iterations on the same column vector in R.

Here is the code:

For the test data, the length of the data is 50

dat <- rnorm(50)        
dat <- data.frame(dat)

function

cv2 = function(a) {

  for(i in 1:nrow(a)) { 

  for(j in 1:nrow(a)) {

  iplus1 = next(a[j])

  return((2*(abs((a[i])-(iplus1)))) / ((a[i])+(iplus1)))

}}}  

The output should create a statistic with a range between 0-2, and be of length equal to 49. So far the return of this function is NULL. Any help would be appreciated. Thanks!

Upvotes: 0

Views: 56

Answers (3)

John Coleman
John Coleman

Reputation: 51998

The described computation is really a computation on vectors. In base R, you could do it like this:

cv2 = function(a){
  n <- length(a)
  2*abs((a[-1]-a[-n])/(a[-1]+a[-n]))
}

and then call it like cv2(dat[1,]) if you want to feed it a column of a dataframe.

Upvotes: 2

fra
fra

Reputation: 852

Not sure about the formula, but in baseR you can use sapply

dat <- data.frame(col1 = rnorm(50), col2 = rnorm(50) )
dat$res <- sapply(1:nrow(dat), function(t) 2*(abs(dat[t,1]-dat[t,2])) / (dat[t,1]+dat[t,2]))

head(dat)
     col1        col2         res
1 -0.62036668  0.45018710 -12.5814602
2  0.04211587 -0.01855983   5.1516048
3 -0.91092165 -0.31806837  -0.9647813
4  0.15802877 -0.92936215  -2.8195096
5 -0.65458464 -1.48746031  -0.7776454
6  1.76728727 -1.07519230   8.2141315

Upvotes: 0

abhilb
abhilb

Reputation: 5757

With the help of dplyr package you can do try this:

> library(dplyr)
> x <- rnorm(50)
> df <- data.frame(x)
> output <- df %>%
+     mutate(y = lag(x)) %>%
+     mutate(result = (2*abs(x-y)) / (x+y))

Which would give you a result like this:

           x            y        result
1  -0.208826981           NA            NA
2  -0.701317391 -0.208826981 -1.082225e+00
3  -0.740003385 -0.701317391 -5.368131e-02
4  -1.162325354 -0.740003385 -4.440052e-01
5  -0.133625594 -1.162325354 -1.587560e+00
6  -1.115008292 -0.133625594 -1.571930e+00
7   0.579094801 -1.115008292 -6.322301e+00
8  -1.194556141  0.579094801 -5.763647e+00
9  -0.131487021 -1.194556141 -1.603370e+00
10  0.646124908 -0.131487021  3.021977e+00
11 -0.551389477  0.646124908  2.528124e+01

Upvotes: 0

Related Questions