Michal
Michal

Reputation: 215

R - dynamic reference to a data frame used within a function

I have a data frame "MyFrame" and I want to create a function which would reference dynamically some elements from this data frame.

A B  
1 11
2 12
3 13
4 14

I want the function to do the following calculation

myfunction(rownumber)=(B[rownumber]-B1)/sum(B1:B[rownumber])

I am trying something like this but it is not working.

myfunction <- function(x) {
    myfunction <- (MyFrame$B[x]-MyFrame$B[1])/(sum(MyFrame$B[2:x])
return(myfunction)}

myfunction(4)=(14-11)/(11+12+13+14)=0.06

I guess it is because the reference is done incorrectly. How this could be done?

Upvotes: 1

Views: 362

Answers (1)

statquant
statquant

Reputation: 14370

Is this what you expect?

library(data.table)
setDT(MyFrame)
MyFrame[,C:=(B[x]-B[1L])/sum(B[1:x])]

Upvotes: 1

Related Questions