analysis - How to separate data in R based on conditions -
i separate data depending on conditions in r data analysis can't figure out how this.
i have data grouped separate based on conditions of grouping. here example of trying do:
original data:
dataset:
trial position data 1 1 70 1 2 73 1 3 80 1 4 75 2 1 41 2 2 80 2 3 45 2 4 70 3 1 50 3 2 53 3 3 50 3 4 53 4 1 80 4 2 90 4 3 85 4 4 53
desired data:
dataset1: trial position data 1 1 70 1 2 73 1 3 80 1 4 75 4 1 80 4 2 90 4 3 85 4 4 53 dataset2: trial position data 2 1 41 2 2 80 2 3 45 2 4 70 3 1 50 3 2 53 3 3 50 3 4 53
i able separate data, such if data in position 1 of each separate trial above 50, entire trial information , data gets put data set , data in position 1 below 50 gets put separate data set. how do this?
we can use split
list
output. create grouping variable ave
checking if first value of 'data' greater 50 each 'trial' group.
lst <- split(dataset, with(dataset, ave(data, trial, fun=function(x) x[1]<=50)))
if need 2 datasets in global environment, name list
elements , use list2env
(not recommended)
names(lst) <- paste0('dataset', seq_along(lst)) lst #$dataset1 # trial position data #1 1 1 70 #2 1 2 73 #3 1 3 80 #4 1 4 75 #13 4 1 80 #14 4 2 90 #15 4 3 85 #16 4 4 53 #$dataset2 # trial position data #5 2 1 41 #6 2 2 80 #7 2 3 45 #8 2 4 70 #9 3 1 50 #10 3 2 53 #11 3 3 50 #12 3 4 53 list2env(lst, envir=.globalenv)
update
if there cases position=1
not found in 'dataset', above code may not work well. creating split
group dplyr
based on condition if position==1 exists , data greater 50, true whole group.
library(dplyr) grp <- dataset %>% group_by(trial) %>% transmute(ind= any(data>50 & position==1))%>% .$ind split(dataset, grp) # $`false` # trial position data #5 2 1 41 #6 2 2 80 #7 2 3 45 #8 2 4 70 #9 3 1 50 #10 3 2 53 #11 3 3 50 #12 3 4 53 #$`true` # trial position data #1 1 1 70 #2 1 2 73 #3 1 3 80 #4 1 4 75 #13 4 1 80 #14 4 2 90 #15 4 3 85 #16 4 4 53
we can rename list elements above , create separate datasets if needed.
Comments
Post a Comment