Adding a column to a dataframe in R

前端 未结 2 1076
野的像风
野的像风 2021-01-30 00:56

I have the following dataframe (df)

 start     end
1    14379   32094
2   151884  174367
3   438422  449382
4   618123  621256
5   698271  714321
6          


        
相关标签:
2条回答
  • 2021-01-30 01:19

    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] ] ))]
    
    0 讨论(0)
  • 2021-01-30 01:22

    That is a pretty standard use case for apply():

    R> vec <- 1:10
    R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
    R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
    R> DF
      start end newcol
    1     1   2    1.5
    2     3   6    4.5
    3     5   7    6.0
    4     7   9    8.0
    R> 
    

    You can also use plyr if you prefer but here is no real need to go beyond functions from base R.

    0 讨论(0)
提交回复
热议问题