rloopsfunction-calls

How to Iterate over a column in a data frame to change its values


I have a data frame that looks like:

ID     A     B    
 0     8    25  
 1    16   123  
 2     4   120  
...             ...

What I want to do now is to iterate over column 'A' for example and call a function with the value of the cell and return it at the same location.

For example a function like (x^2)-1.

int calculation(int val){
   return val*val-1;
}

...code...

while(i<A.length){
  A[i] = calculation(A[i]);
}

So the result should look like this.

ID     A     B    
 0    63    25  
 1   265   123  
 2    15   120  
...             ...




I am new to R, if you know some good basic guidelines or books for scientific plotting, let me know. :-)

Thanks for your help.


Solution

  • This is very straightforward task in R.

    a<-c(8,16,4)
    b<-c(25,123,120)
    df<-data.frame(a,b)
    
    calculation<-function(a){
      a^2-1
    }
    
    
    # Method 1
    df$a<-(df$a^2)-1
    
    # Method 2
    df$a<-calculation(df$a)