filter - R: how to split list into AM/PM -


the time stamp on survey grouped of data 1 column under starttime, need split data , pm groups.

for example, right data looks

8:37 pm 3:58 pm 10:22 2:48 pm 6:33 pm 7:10 10:59 

but need divide into

8:37 pm  10:22 3:58 pm  7:10 2:48 pm 10:59 6:33 pm 

any ideas on how this? thanks

you can use split

split(df1, grepl('pm', df1$starttime)) 

if need data.frame 2 columns

 lst <- split(df1$starttime, grepl('pm', df1$starttime))  setnames(data.frame(lapply(lst, `length<-`, max(lengths(lst)))),                    c('am', 'pm'))  #            pm  #1 10:22 8:37 pm  #2  7:10 3:58 pm  #3 10:59 2:48 pm  #4     <na> 6:33 pm 

or

 library(data.table)#v1.9.5+  dcast(setdt(df1)[, group:= c('am', 'pm')[grepl('pm', starttime)+1l]][,            n:=1:.n, group], n~group, value.var='starttime')  #   n            pm  #1: 1 10:22 8:37 pm  #2: 2  7:10 3:58 pm  #3: 3 10:59 2:48 pm  #4: 4       na 6:33 pm 

or using dplyr/tidyr

library(dplyr) library(tidyr) df1 %>%      extract(starttime, into='ampm', '[^ ]+\\s+([^ ]+)', remove=false) %>%     group_by(ampm) %>%     mutate(n=row_number()) %>%      spread(ampm, starttime) 

data

 df1 <- structure(list(starttime = c("8:37 pm", "3:58 pm", "10:22 am",   "2:48 pm", "6:33 pm", "7:10 am", "10:59 am")), .names = "starttime",   class = "data.frame", row.names = c(na, -7l)) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -