user330
user330

Reputation: 1270

How to sort these types of the data in R

I have 30 columns and I want to sort them. It seems multi packages are required, but I struggle to do it. Here is a sample of data:

df<-read.table (text=" Id   Name    Class   bc1 M1  G1
23  Smith   A1  13  13  12
19  John    Z1  12  14  12
33  Rose    OG1 14  13  14
66  Javid   MO1 12  14  13
66  Javid   MO2 12  13  14
23  Smith   A11 12  13  12
33  Rose    OG2 14  14  13
19  John    Z11 12  12  12

", header=TRUE)

And I want to get these data:

Id  Name    Class1  bc1 M1  G1  Class2  bc1 M1  G1
23  Smith   A1  13  13  12  A11 12  13  12
19  John    Z1  12  14  12  Z11 12  12  12
33  Rose    OG1 14  13  14  OG2 14  14  13
66  Javid   MO1 12  14  13  MO2 12  13  14

The logic is that each Id has different values and I want to generate columns for them. Thank you for your help.

Upvotes: 1

Views: 31

Answers (1)

akrun
akrun

Reputation: 887118

We can create a sequence column and then use pivot_wider

library(tidyr)
library(dplyr)
library(data.table)
library(stringr)
df %>%
   mutate(nm1 = rowid(Id, Name)) %>%
   pivot_wider(names_from = nm1, values_from = Class:G1)%>%
   select(Id, Name, order(as.integer(str_remove(names(.)[-(1:2)], ".*_"))) + 2)

-output

# A tibble: 4 x 10
#     Id Name  Class_1 bc1_1  M1_1  G1_1 Class_2 bc1_2  M1_2  G1_2
#  <int> <chr> <chr>   <int> <int> <int> <chr>   <int> <int> <int>
#1    23 Smith A1         13    13    12 A11        12    13    12
#2    19 John  Z1         12    14    12 Z11        12    12    12
#3    33 Rose  OG1        14    13    14 OG2        14    14    13
#4    66 Javid MO1        12    14    13 MO2        12    13    14

Upvotes: 1

Related Questions