Last active
September 2, 2015 23:40
-
-
Save tdunning/192356932d7d9ed39e00 to your computer and use it in GitHub Desktop.
Some code that reads data in SVM Light format and returns a list of target and data. The data is stored in a sparse matrix to make this a bit more memory efficient.
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
require(Matrix) | |
read.svmlight2 <- function( filename ) { | |
f <- file( filename, "r") | |
lines = readLines( f ) | |
close(f) | |
temp = strsplit(lines,'[: ]') | |
target = sapply(temp, function(row){as.numeric(row[1])}) | |
raw = lapply(temp, function(row){ | |
n = length(row); | |
matrix(as.numeric(row[-1]), ncol=2, byrow=T) | |
}) | |
data = do.call('rbind', mapply(cbind, x=1:n, y=raw)) | |
list(target=target, data=sparseMatrix(x=data[,3], i=data[,1], j=data[,2])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks very useful, but when I tried to use this function I received the error: object 'n' not found. Any advice appreciated.