1

For on the dataframe AB:

AB<-data.frame(ID=c(1,2,4),A=c(2,8,8),B=c(6,2,2),dE=c(0,0,0))

I would like to apply the following formula: AB$dE=AB$B/AB$A

ID A  B  dE
1  2  6  0
2  8  2  0
4  8  2  0

to convert the above to:

ID A  B  dE
1  2  6  3
2  8  2  0.25
4  8  2  4

because I have several files that contain different column names for A and B, it would be more practical to write a function, something like

dEs <- function(data,nume,denom){ 
        #define which datafile and numerator/denom column
        #so in case of AB this becomes AB$dE; 
        # i dont know the correct way to do this.
        dE=data.'$dE'
        start=data.'$'.nume #to become AB$A
        end=data.'$'.denom #to become AB$B
        for(i in data){
          dE[i] <- (start[i]/end[i])
        }
}

this way I would be able to change the numerator/denominator when necessary.

1
  • It is nonsense to write a function here, since you don't need any loop -- just write AB$dE=AB$B/AB$A (or better AB$dE<-AB$B/AB$A). Commented Oct 13, 2011 at 12:33

1 Answer 1

2

You don't need a loop, since R is vectorized:

> AB <- data.frame(ID=c(1,2,4),A=c(2,8,8),B=c(6,2,2),dE=c(0,0,0))
> AB <- transform(AB, dE=B/A)
> AB
  ID A B   dE
1  1 2 6 3.00
2  2 8 2 0.25
3  4 8 2 0.25

If you really want a function, you can use [[]] to select columns, since a data.frame is just a list (assuming nume and denom are character vectors with the name of the column you want):

dEs <- function(data,nume,denom){ 
  data$dE <- data[[nume]] / data[[denom]]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.