[r] Adding a column to a dataframe in R

I have the following dataframe (df)

 start     end
1    14379   32094
2   151884  174367
3   438422  449382
4   618123  621256
5   698271  714321
6   973394  975857
7   980508  982372
8   994539  994661
9  1055151 1058824
.   .       .
.   .       .
.   .       .

And a long vector with numeric values (vec).

I would like to add to each row another column, with the mean of the values in the corresponding places in vec. for example, the first row will have mean(vec[14379:32094]). I have tried playing with transform but wasn't able to accomplish this simple task.

This question is related to r dataframe

The answer is


Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]