Pages

31 August, 2023

Taking mean of consequitive non NA values in data table in R

For the below data table library(data.table) test = data.table(date = c("2006-01-31", "2006-03-20", "2006-03-28", "2006-05-03", "2006-05-04", "2006-06-29", "2006-09-11"), value = c(NA, -0.028, NA, 0.0245, -0.008, NA, -0.009)) I need the mean of consequitive Non NA values as a separate column in the above data table. For eg, the resultant data table would look like this library(data.table) test = data.table(date = c("2006-01-31", "2006-03-20", "2006-03-28", "2006-05-03","2006-05-04", "2006-06-29", "2006-09-11"), value = c(NA, -0.028, NA, 0.0245, -0.008, NA, -0.009), value_new = c(NA, -0.028, NA,0.008, 0.008, NA, -0.009)) Tried doing this using rle and data table functions but not getting the correct output. Thanks in advance

No comments:

Post a Comment

Thanks