gosia
gosia

Reputation: 131

R separating values between columns

I've got a problem with my data.

My problem is the following. I've got a column with values as below: data <- c(1,2,4,6,8,13,14,16)

In new data frame I want to write down in separate columns the values until the difference between the first and each subsequent is less than 10 (for ex. 2-1<10, 8-1<10 but 13-1>10 -> so 13 is the first value in second column). Values can not be repeated in different columns. Example output below:

1   13
2   14
4   16
6    0
8    0

Could you help me, please?

Upvotes: 0

Views: 63

Answers (1)

Benjamin
Benjamin

Reputation: 17369

Here's one approach. (Edited to reflect new problem description)

data <- c(1,2,4,6,8,13,14,16)

D2 <- split(data, (data - data[1]) %/% 10)

max_length <- max(lengths(D2))

D2 <- lapply(D2,
       function(d, m) c(d, rep(0, m - length(d))),
       max_length) 
(D2 <- as.data.frame(D2))

Upvotes: 1

Related Questions