简体   繁体   中英

Split a data.table at position

I want to calculate the mean of a column in a data.table way by using row numbers or a vector with position.

Here is a sample data and a postion vector:

x <- data.table(a = c(1,2,3,4,5,6,7,8))
pos <- c(3,5)

I tried:

x[mean(a), by = pos]

So i want the mean from row 1:2, 3:4 and 5:8.

Here is an option:

x[, mean(a), cumsum(replace(rep(0, nrow(x)), pos, 1L))]

output:

   cumsum  V1
1:      0 1.5
2:      1 3.5
3:      2 6.5

You can use findInterval / cut to create groups based on pos :

library(data.table)
x[, mean(a), findInterval(a, pos)]

#   findInterval  V1
#1:            0 1.5
#2:            1 3.5
#3:            2 6.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM