开发者

create loop function for calculating value of one column from other column in R

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){开发者_如何学Go 
        #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.


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]]
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜