Home > Blockchain >  How to sort out this data in R
How to sort out this data in R

Time:01-15

Here is a sample of my data

dat<-read.table (text=" ID  GO  Class   N1  L1  K1
1   1   01-03   0   3   4
2   3   01-03   0   3   6
3   2   01-03   0   5   5
4   5   01-03   0   2   1
1   6   01-03   0   1   1
", header=TRUE)

I want to repeat ID and GO.
Next, I want to create zeros for the repeated columns for the Column Class.
Next, I want to create 1 for the repeated columns for the Column N1. The repeated columns for L1 and K1 would be NA

Here is the outcome

  ID    GO  Class   N1  L1  K1
    1   1   01-03   0   3   4
    1   1   0       1       
    2   3   01-03   0   3   6
    2   3   0   1       
    3   2   01-03   0   5   5
    3   2   0   1       
    4   5   01-03   0   2   1
    4   5   0   1
    1   6   01-03   0   1   1   
    1   6     0     1

I have tried

dat %>% slice(rep(1:n(), each = 2))

This does not help me.

CodePudding user response:

To maintain the order of the original data we can have a new column with the row number. Fill Class and N1 with "0" and 1 value and bind it to the original data.

library(dplyr)

dat <- dat %>% mutate(row = row_number()) 

dat %>%
  transmute(ID, GO, row, Class = "0", N1 = 1) %>%
  bind_rows(dat, .) %>%
  arrange(row) %>%
  select(-row)

#   ID GO Class N1 L1 K1
#1   1  1 01-03  0  3  4
#2   1  1     0  1 NA NA
#3   2  3 01-03  0  3  6
#4   2  3     0  1 NA NA
#5   3  2 01-03  0  5  5
#6   3  2     0  1 NA NA
#7   4  5 01-03  0  2  1
#8   4  5     0  1 NA NA
#9   1  6 01-03  0  1  1
#10  1  6     0  1 NA NA
  •  Tags:  
  • r
  • Related