Home > Software design >  Repeat a sequence of values until end in a dataframe colum
Repeat a sequence of values until end in a dataframe colum

Time:11-01

In R, I have a very long dataframe in which there are two columns as follows:

up low
5 10
10 20
20 30
NA NA
NA NA
NA NA
NA NA
NA Na
NA NA

I would like to repeat the sequence of numbers in these two columns until the end of the dataframe. So, my desired table should look like this:

up low
5 10
10 20
20 30
5 10
10 20
20 30
5 10
10 20
20 30

How can I do it in R? What codes can be used to do this? Please help me. Thanks

CodePudding user response:

I would use rep and row.names:

> df[rep(row.names(na.omit(df)), nrow(df) / nrow(na.omit(df))),]
    up low
1    5  10
2   10  20
3   20  30
1.1  5  10
2.1 10  20
3.1 20  30
1.2  5  10
2.2 10  20
3.2 20  30
> 

To reset the index:

out <- df[rep(row.names(na.omit(df)), nrow(df) / nrow(na.omit(df))),]
row.names(out) <- NULL

> out
  up low
1  5  10
2 10  20
3 20  30
4  5  10
5 10  20
6 20  30
7  5  10
8 10  20
9 20  30
> 

CodePudding user response:

How about replicating the data frame without the NAs, i.e.

sapply(na.omit(df),rep.int,times=(nrow(df) / nrow(na.omit(df))))
#      v1 v2
# [1,]  5 10
# [2,] 10 20
# [3,] 20 30
# [4,]  5 10
# [5,] 10 20
# [6,] 20 30
# [7,]  5 10
# [8,] 10 20
# [9,] 20 30

CodePudding user response:

here is a tidyverse approach using purrr:

purrr::map_dfr(seq_len(3), ~df) %>% 
  na.omit()
   up low
1   5  10
2  10  20
3  20  30
10  5  10
11 10  20
12 20  30
19  5  10
20 10  20
21 20  30
  • Related