Reputation: 1403
I have a data frame like this:
Values
1
2
3
.
.
1000
I want to break it into a data frame with 10 columns based on rows. So rows 1-100 goes in one column, rows 101-200 goes in the second column and so on resulting in the final data set as below:
Col1 Col2............... Col10
1 101 901
2 102 902
3 103 903
. .
. .
100 200 1000
Upvotes: 0
Views: 63
Reputation:
An alternative is using the do.call which execute and construct a function call coming from rbind which takes a sequence of list consturcted by lapply arguments and combine it by columns
df <- data.frame(Values=1:1000)
mydf <- data.frame(do.call(rbind,lapply(df,matrix, ncol=10)))
names(mydf) <- paste0("Col", 1:10)
If you don't like to use paste0 to set the column names, you can use sprintf
names(mydf) <-sprintf("Col%d", 1:10)
> head(mydf,5)
# Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 Col10
#1 1 101 201 301 401 501 601 701 801 901
#2 2 102 202 302 402 502 602 702 802 902
#3 3 103 203 303 403 503 603 703 803 903
#4 4 104 204 304 404 504 604 704 804 904
#5 5 105 205 305 405 505 605 705 805 905
Upvotes: 1
Reputation: 38510
Here is one method:
dfNew <- data.frame(matrix(unlist(df), 100))
names(dfNew) <- paste0("Col", 1:10)
The first line coerces the data.frame to a vector (unlist
), then to a matrix with rows of length 100 (matrix
). This matrix is then converted to a data.frame (data.frame
).
Here are the first 6 rows:
head(dfNew)
Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 Col10
1 1 101 201 301 401 501 601 701 801 901
2 2 102 202 302 402 502 602 702 802 902
3 3 103 203 303 403 503 603 703 803 903
4 4 104 204 304 404 504 604 704 804 904
5 5 105 205 305 405 505 605 705 805 905
6 6 106 206 306 406 506 606 706 806 906
The second line adds the data.frame names.
data
df <- data.frame(Values=1:1000)
Upvotes: 1