Home > Software design >  How we could sort this datata frame out in R
How we could sort this datata frame out in R

Time:01-30

My data are as follows:

dat <- read.table(text = " ID   X1  X2  X3  X4  X5  X6  X7  X8  X9  X10 X11 X12 X13 X14 X15 X16
1   14  14  13  19  13  10  13  10  12  16  10  12  11  15  18  19
2   13  16  10  17  13  18  13  13  13  12  13  15  17  12  17  20
3   10  14  15  14  13  10  17  15  19  12  11  15  11  17  20  16
", header = TRUE)

The expected outcome is:

    ID  X1  X2  X3  X4
    1   14  14  13  19
    2   13  16  10  17
    3   10  14  15  14
    1   13  10  13  10
    2   13  18  13  13
    3   13  10  17  15
    1   12  16  10  12
    2   13  12  13  15
    3   19  12  11  15
    1   11  15  18  19
    2   17  12  17  20
    3   11  17  20  16

Imaging 16 columns and three Ids, the first four columns ( X1 to X4) for IDs 1,2 and 3, the second four column (X5 to X8) are staked for IDs 1,2 and 3 and so on

CodePudding user response:

An option could be by first splitting the data by every four columns using split_default into a list with each columns. Then use bind_rows to combine them by stacking and unite and separate to remove the NA's to have the 4 columns like this:

library(dplyr)
library(tidyr)

l <- split.default(dat[,-1], rep(1:4, each = 4))

bind_rows(l) %>% 
  unite(result, everything(), na.rm = TRUE) %>%
  separate(result, into = paste0("X", c(1:4))) %>%
  mutate(ID = rep(c(1:3), 4))
#>    X1 X2 X3 X4 ID
#> 1  14 14 13 19  1
#> 2  13 16 10 17  2
#> 3  10 14 15 14  3
#> 4  13 10 13 10  1
#> 5  13 18 13 13  2
#> 6  13 10 17 15  3
#> 7  12 16 10 12  1
#> 8  13 12 13 15  2
#> 9  19 12 11 15  3
#> 10 11 15 18 19  1
#> 11 17 12 17 20  2
#> 12 11 17 20 16  3

Created on 2023-01-29 with reprex v2.0.2

CodePudding user response:

This is another suggestion without using any package.

rdx=1:3
helperfun=function(x) c(1,( (x*4 2) :((x*4 2) 3)))
mapply(c, dat[ rdx , helperfun(0)], dat[ rdx,  helperfun(1)], dat[ rdx, helperfun(2)], dat[ rdx, helperfun(3)]  )

The result:

      ID X1 X2 X3 X4
 [1,]  1 14 14 13 19
 [2,]  2 13 16 10 17
 [3,]  3 10 14 15 14
 [4,]  1 13 10 13 10
 [5,]  2 13 18 13 13
 [6,]  3 13 10 17 15
 [7,]  1 12 16 10 12
 [8,]  2 13 12 13 15
 [9,]  3 19 12 11 15
[10,]  1 11 15 18 19
[11,]  2 17 12 17 20
[12,]  3 11 17 20 16

Based on the comment, here is another suggestion.

rdx=1:3
helperfun=function(x) c(1,( (x*4 2) :((x*4 2) 3)))
df=dat[ rdx , helperfun(0)]
for (i in 1:3)
{
  tmp=dat[ rdx,  helperfun(i)]
  names(tmp)=names(df)
  df=rbind(df, tmp)
}
  •  Tags:  
  • r
  • Related