Home > front end >  How perform rbind fucntion by prefix using R
How perform rbind fucntion by prefix using R

Time:04-20

suppose i have dataset

dat=structure(list(X0_B02 = c(108L, 280L, 362L, 918L, 141L), X0_B03 = c(398L, 
733L, 725L, 1116L, 421L), X0_B04 = c(214L, 464L, 692L, 1394L, 
238L), X1_B02 = c(480L, 484L, 544L, 911L, 380L), X1_B03 = c(760L, 
856L, 849L, 1110L, 611L), X1_B04 = c(546L, 599L, 737L, 1348L, 
431L)), class = "data.frame", row.names = c(NA, -5L))

0_, 1_ these are prefixes to variables. 0_ means zero day, 1_ means the first day, 2_ will mean the second day of observations for variables bo2, bo3, bo4. I need to make that the variables for days will not in columns but in rows, with indicating the day. Like this.

day B02 B03 B04
0   108 398 214
0   280 733 464
0   362 725 692
0   918 1116    1394
0   141 421 238
1   480 760 546
1   484 856 599
1   544 849 737
1   911 1110    1348
1   380 611 431

is the way using rbind fucntion perform it or to get desired output we need another way? Thank you.

CodePudding user response:

Using tidyverse, you can use pivot_longer with a names_pattern. This will allow the number after "X" to be used for the new day column, and the word after underscore for the other column names.

library(tidyr)

pivot_longer(
  dat,
  cols = everything(),
  names_to = c("day", ".value"),
  names_pattern = "X(\\d )_(\\w )"
)

Output

   day     B02   B03   B04
   <chr> <int> <int> <int>
 1 0       108   398   214
 2 1       480   760   546
 3 0       280   733   464
 4 1       484   856   599
 5 0       362   725   692
 6 1       544   849   737
 7 0       918  1116  1394
 8 1       911  1110  1348
 9 0       141   421   238
10 1       380   611   431
  •  Tags:  
  • r
  • Related