Advertisement
celestialgod

select specific row by ID

Mar 9th, 2016
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.37 KB | None | 0 0
  1. library(data.table)
  2. library(magrittr)
  3. library(dplyr)
  4.  
  5. DT <- fread('
  6. ID   性別     年齡   號碼
  7. 1      F       23      2
  8. 1      F       30      2
  9. 1      M       32      2
  10. 2      M       32      1
  11. 2      F       23      1
  12. 3      M       56      1
  13. 3      F       23      1
  14. 3      M       18      1
  15. 4      M       12      4
  16. 4      F       32      4
  17. 4      M       65      4
  18. 4      F       45      4
  19. 4      M       42      4
  20. ') %>% tbl_dt(FALSE)
  21.  
  22. select_rows_f <- function(scheme, DT){
  23.   switch(scheme,
  24.     A = {
  25.       outDT = DT %>% arrange(ID, 年齡) %>%
  26.         mutate(selectRowID = round(號碼*(0.5+1e-6))) %>%  
  27.         # +1e-6是因為 round(0.5)是0,要比0.5大一點點才會進位
  28.         group_by(ID) %>% summarise(性別 = 性別[unique(selectRowID)],
  29.         年齡 = 年齡[unique(selectRowID)], 號碼 = 號碼[unique(selectRowID)])
  30.         ## use summarise_each 另外兩個例子,可以自己改XD
  31.         # outDT = DT %>% arrange(ID, 年齡) %>%
  32.         #   group_by(ID) %>% summarise_each(funs(.[unique(round(號碼*(0.5+1e-6)))]))
  33.     },
  34.     B = {
  35.       outDT = DT %>% arrange(ID, desc(年齡)) %>%
  36.         mutate(selectRowID = round(號碼*0.9)) %>%
  37.         group_by(ID) %>% summarise(性別 = 性別[unique(selectRowID)],
  38.         年齡 = 年齡[unique(selectRowID)], 號碼 = 號碼[unique(selectRowID)])
  39.     },
  40.     C = {
  41.       outDT = DT %>% arrange(ID, desc(年齡)) %>%
  42.         mutate(selectRowID = 號碼) %>%
  43.         group_by(ID) %>% summarise(性別 = 性別[unique(selectRowID)],
  44.         年齡 = 年齡[unique(selectRowID)], 號碼 = 號碼[unique(selectRowID)])
  45.     })
  46.   return(outDT)
  47. }
  48. select_rows_f('A', DT)
  49. # Source: local data table [4 x 4]
  50. #
  51. #      ID  性別  年齡  號碼
  52. #   (int) (chr) (int) (int)
  53. # 1     1     F    23     2
  54. # 2     2     F    23     1
  55. # 3     3     M    18     1
  56. # 4     4     F    32     4
  57. select_rows_f('B', DT)
  58. # Source: local data table [4 x 4]
  59. #
  60. #      ID  性別  年齡  號碼
  61. #   (int) (chr) (int) (int)
  62. # 1     1     F    30     2
  63. # 2     2     M    32     1
  64. # 3     3     M    56     1
  65. # 4     4     F    32     4
  66. select_rows_f('C', DT)
  67. # Source: local data table [4 x 4]
  68. #
  69. #      ID  性別  年齡  號碼
  70. #   (int) (chr) (int) (int)
  71. # 1     1     F    30     2
  72. # 2     2     M    32     1
  73. # 3     3     M    56     1
  74. # 4     4     F    32     4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement