Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206209

Applying a function to each element of a group in R data frame

$
0
0

I am trying to find the first non-NA element of column w in each group and then construct a new variable which starts from the index of that non-NA element and follows this law of motion: k_{it+1}=k_{it}+s_{it+1}-s{it}.

i denotes the group and t is time. k_{i1} comes from the first non-NA element of column w.

Let's say I have the following dataset:

 DF <- data.frame("time"=factor(c(1999,2000,2001,2002,1999,2000,2001,2002)),
             "i"=factor(c("a","a","a","a","b","b","b","b")),
             "w"=c(NA,1,2,4,4,NA,3,4), "s"= c(10,20,10,22,45,30,20,40))

And I want to add a new column to it:

DF$k <- c(NA, 1, -9, 3, 4, -11, -21, -1)


Viewing all articles
Browse latest Browse all 206209

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>