Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. df1 <- data.frame(time=seq(0.0, by = 0.003, length.out = 1000))
  2.  
  3. time
  4. 1 0.000
  5. 2 0.003
  6. 3 0.006
  7. 4 0.009
  8. 5 0.012
  9. 6 0.015
  10. ...
  11.  
  12. df2 <- data.frame(onset=c(0.0, 0.8, 1.9, 2.4), offset=c(0.799, 1.899, 2.399, 3.0))
  13.  
  14. onset offset A B
  15. 1 0.0 0.799 ... ...
  16. 2 0.8 1.899 ... ...
  17. 3 1.9 2.399 ... ...
  18. 4 2.4 3.000 ... ...
  19.  
  20. df1$onset <- df2$onset[findInterval(df1$time, df2$onset)]
  21. df3 <- merge(df1, df2, by = "onset")
  22.  
  23. head(df3)
  24. # onset time offset
  25. # 1 0 0.000 0.799
  26. # 2 0 0.003 0.799
  27. # 3 0 0.006 0.799
  28. # 4 0 0.009 0.799
  29. # 5 0 0.012 0.799
  30. # 6 0 0.015 0.799
  31.  
  32. tail(df3)
  33. # onset time offset
  34. # 995 2.4 2.982 3
  35. # 996 2.4 2.985 3
  36. # 997 2.4 2.988 3
  37. # 998 2.4 2.991 3
  38. # 999 2.4 2.994 3
  39. # 1000 2.4 2.997 3
  40.  
  41. # breaks for 'cut'
  42. times=c(df2$onset[1],df2$offset)
  43.  
  44. # modified df1 to shorten the list
  45. df1 <- data.frame(time=seq(0.0, by = 0.03, length.out = 100))
  46.  
  47. # Add a few columns to df2
  48. df2 <- data.frame(onset=c(0.0, 0.8, 1.9, 2.4), offset=c(0.799, 1.899, 2.399, 3.0), A=c(1,2,3,4), B=c(5,6,7,8))
  49.  
  50.  
  51. df2$ranges <-cut(df2$onset,times,include.lowest=T))
  52. df1$ranges <-cut(df1$time,times,include.lowest=T,levels=levels(df2$ranges))
  53.  
  54. join(df1,df2,by='ranges')
  55.  
  56. head(join(df1,df2,by='ranges')[-2])
  57. time onset offset A B
  58. 1 0.00 0 0.799 1 5
  59. 2 0.03 0 0.799 1 5
  60. 3 0.06 0 0.799 1 5
  61. 4 0.09 0 0.799 1 5
  62. 5 0.12 0 0.799 1 5
  63. 6 0.15 0 0.799 1 5
  64.  
  65. > head(sqldf("select *
  66. + from df1 inner join df2
  67. + on (df1.time between df2.onset and df2.offset)"))
  68.  
  69. time onset offset
  70. 1 0.000 0 0.799
  71. 2 0.003 0 0.799
  72. 3 0.006 0 0.799
  73. 4 0.009 0 0.799
  74. 5 0.012 0 0.799
  75. 6 0.015 0 0.799
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement