I have a long list that looks something like this:
Sample 1
1
2
3
Sample 2
4
5
6
Sample 3
7
8
9
And I would like to turn it into this:
Sample 1 Sample 2 Sample 3
1 4 7
2 5 8
3 6 9
I'm guessing the solution would be to possibly grep "Sample" and somehow move everything that's under it into a new column, but I cannot figure out how to do that (especially without any packages). Any help would be appreciated.
CodePudding user response:
assuming the samples size is the same, transform list to matrix
list <- list('Sample 1',
'1',
'2',
'3',
'Sample 2',
'4',
'5',
'6',
'Sample 3',
'7',
'8',
'9')
mat <- matrix(list,nrow = 4)
colnames(mat) <- mat[1,] # first row as names
df <- as.data.frame(mat[-1,]) # remove names form first row & convert to data.frame
out
Sample 1 Sample 2 Sample 3
1 1 4 7
2 2 5 8
3 3 6 9
CodePudding user response:
Assuming that the pattern is repeated an equal number of times, an option would be to split the df up into equal parts, into a list, and then bind the list into columns:
library(rlist)
n=4
nr=nrow(dat)
list.cbind(split(dat, rep(1:ceiling(nr/n), each=n, length.out=nr)))
1.V1 2.V1 3.V1
1: Sample 1 Sample 2 Sample 3
2: 1 4 7
3: 2 5 8
4: 3 6 9
dat = fread('Sample 1
1
2
3
Sample 2
4
5
6
Sample 3
7
8
9 ', header=F)