Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split frame into list by user-defined cutoff

Tags:

r

would like to split a df frame into nested df.listing list by cutoff index_cutoff :

Data:

df <- data.frame(m=c("A","T","W","Z","B","A","A","W","T","K","G","B","T","B"))
index_cutoff <- c("A","B")

Attempt Code:

df.listing <- split(df, df$m %in% keyword_cutoff) #failed, not working

Current Output:

$`FALSE`
   m
2  T
3  W
4  Z
8  W
9  T
10 K
11 G
13 T

$`TRUE`
   m
1 A
5 B
6 A
7 A
12 B
14 B

Desired Output Stage 1:

df.listing[[1]]
A
T
W
Z

df.listing[[2]]
B

df.listing[[3]]
A

df.listing[[4]]
A
W
T
K
G

df.listing[[5]]
B
T

df.listing[[6]]
B

Desired Output Final:

df.listing[[1]]
A
T
W
Z

df.listing[[2]]
B

df.listing[[3]]
A #since at stage 1 they are the same cutoff, hence self merge into next list
A
W
T
K
G

df.listing[[4]]
B #since at stage 1 they begin the same with "B" cutoff
T
B

thank you and apologies for not able to come out with reproducible examples via R datasets.

like image 393
beavis11111 Avatar asked Mar 06 '23 04:03

beavis11111


2 Answers

We need to take a cumulative sum of the logical index as split group

split(df, cumsum(df$m %in% index_cutoff))

In the OP's code, there is only two groups i.e. TRUE and FALSE from df$m %in% index_cutoff. By doing cumsum, it gets changed by adding 1 at every TRUE value

like image 120
akrun Avatar answered Mar 20 '23 17:03

akrun


You can try something like

library(dplyr)
library(zoo)

df1 <- df %>%
  mutate_if(is.factor, as.character) %>%
  mutate(grp = ifelse(m %in% index_cutoff, row_number(), NA))

df2 <- df1 %>%
  filter(!is.na(grp)) %>%
  mutate(new_grp = na.locf(ifelse(m != lag(m, default='0'), grp, NA))) %>%
  right_join(df1, by = c("m", "grp")) %>%
  select(-grp) %>%
  mutate(new_grp = na.locf(new_grp)) 

which gives the final desired grouping as

df2
#   m new_grp
#1  A       1
#2  T       1
#3  W       1
#4  Z       1
#5  B       5
#6  A       6
#7  A       6
#8  W       6
#9  T       6
#10 K       6
#11 G       6
#12 B      12
#13 T      12
#14 B      12

Now when you run

split(df2$m, df2$new_grp)

you'll get

$`1`
[1] "A" "T" "W" "Z"

$`5`
[1] "B"

$`6`
[1] "A" "A" "W" "T" "K" "G"

$`12`
[1] "B" "T" "B"
like image 27
1.618 Avatar answered Mar 20 '23 17:03

1.618