here's a small example from my dataset
Time <- c(0.1, 0.2, 0.3, 0.1, 0.3)
Individual <- c("A", "A", "A", "B", "B")
data <- data.frame(Individual, Time)
data$Individual <- as.character(data$Individual)
Individual Time
1 A 0.1
2 A 0.2
3 A 0.3
4 B 0.1
5 B 0.3
I wish to create a new column named "Interval" that would represent the interval of Time between each line for every individual. The targetted output for the Interval column would be "na", 0.1, 0.1, "na", 0.2.
I made a list of individuals
ind.id<-unique(data$Individual)
ind.list<-lapply(1:length(ind.id), function(i){subset(data, data$Individual==ind.id[i])})
But the only thing that is missing is the function to calculate de difference between the Time lines for each indidividual from the list and to put it back in an usable dataframe. Any ideas?
Thanks a lot, your help is really appreciated.
An R base solution using ave:
data$val <-
ave(data$Time,data$Individual,FUN=function(x)c(NA,diff(x)))
# Individual Time val
# 1 A 0.1 NA
# 2 A 0.2 0.1
# 3 A 0.3 0.1
# 4 B 0.1 NA
# 5 B 0.3 0.2
Try this:
library(plyr)
ddply(data,.(Individual),transform,val = c(NA,diff(Time)))
Individual Time val
1 A 0.1 NA
2 A 0.2 0.1
3 A 0.3 0.1
4 B 0.1 NA
5 B 0.3 0.2
Faster alternative will be possible using data.table or dplyr packages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With