adk_53
adk_53

Reputation: 13

Applying a function to modify odd and even rows in R dataframe column

I am trying to create a function that loops over a dataframe column and replace values in odd rows (j) using the formula j/j+lead(j), where lead(j) is the value in the next (even) row. In turn, I want to replace values in even rows with formula j/j+lag(j) where lag(j) is the value from the proceeding (odd) row.

I am running into two problems:

  1. The function as written is returning NA's for the replacement values.
  2. The replacements for odd & even should be based on the original column values.

The obvious approach would be to create a second column for the replacement values so that the original column remains intact. However, I haven't gotten to that point.

I'd appreciate any suggestions to: a) correct my code so that it does not produce NA's; b) modify the code so that the calculated values are included a second column (row for row) rather than replacing those in the original column.

I am trying to do this without using pipes and mutate - for practice. However, it would be helpful to see other approaches that I could take to accomplish the same ends with less code.


x<-(c(4,3,5,6,2,1))

df<-as.data.frame(x)

func<- function(x){
    
    for(i in seq(1,length(x))){
        for(j in x){
            if(i%%2 == 1){
                j = j/lead(j)+j}
    
            else if(i%%2 == 0){
                j = j/lag(j)+j}
            }
        show(j)    
    }

}


func(df$x)

Upvotes: 0

Views: 1254

Answers (1)

Waldi
Waldi

Reputation: 41220

Two approaches, with loopor dplyr:

``` r
x<-(c(4,3,5,6,2,1))

df<-as.data.frame(x)

func<- function(x){
  res <- rep(NA,length(x))
  for(i in seq(1,length(x))){
      if(i%%2 == 1){
        res[i] = x[i]/ifelse(i==length(x),NA,x[i+1])+x[i]}
      
      else if(i%%2 == 0){
        res[i] = x[i]/ifelse(i==1,NA,x[i-1])+x[i]}
  }
  res
}

func(df$x)
#> [1] 5.333333 3.750000 5.833333 7.200000 4.000000 1.500000

library(dplyr)

df %>% mutate(x = ifelse(row_number()%%2, x/lead(x)+x ,x/lag(x)+x))
#>          x
#> 1 5.333333
#> 2 3.750000
#> 3 5.833333
#> 4 7.200000
#> 5 4.000000
#> 6 1.500000

Upvotes: 1

Related Questions