Last active
August 29, 2015 14:22
-
-
Save mrdwab/d4134bcb2a6e288447eb to your computer and use it in GitHub Desktop.
SO30528592
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| tableMaker <- function(invec) { | |
| ## http://stackoverflow.com/q/30528592/1270695 | |
| require(data.table) | |
| ## Split up the vector | |
| temp <- strsplit(invec, ",", TRUE) | |
| ## How long is each vector? | |
| a <- lengths(temp) | |
| ## Which vectors need adjustment? | |
| ind <- which(a %% 2 == 0) | |
| ## Adjust only those that need adjustment | |
| temp[ind] <- lapply(temp[ind], function(x) { | |
| c(x[1:(length(x)-1)], x[length(x)-2], x[length(x)]) | |
| }) | |
| ## Recalculate lengths | |
| a <- lengths(temp) | |
| ## Figure out where the IDs are | |
| a2 <- c(1, cumsum(a[-length(a)]) + 1) | |
| ## Unlist the data | |
| tempUL <- unlist(temp) | |
| ## Grab the IDs and repeat them to the necessary length | |
| ID <- rep(tempUL[a2], a/2) | |
| ## Make a 2 column matrix from the remaining values | |
| MAT <- matrix(tempUL[-a2], ncol = 2, byrow = TRUE, | |
| dimnames = list(NULL, c("X", "Z"))) | |
| ## Combine it into a data.table and run type.convert | |
| data.table(ID, MAT)[, lapply(.SD, type.convert)] | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test case: