Created
July 15, 2015 13:25
-
-
Save doug-friedman/ba976f57b1933bb2b176 to your computer and use it in GitHub Desktop.
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
##################### | |
### COLS FUNCTION ### | |
##################### | |
require(readr) | |
## Given the file, fields, and their classes, R will import only the relevant columns | |
## Instead of full class names, you should use the following naming conventions... | |
## c = character, d = double, i = integer, l = logical | |
## see read_csv documentation for more information | |
extract_Cols = function(file="", fields, fields.class, n_max=-1){ | |
# Read the first line of the file | |
first.line = read_csv(file, n_max=1) | |
# Check that the fields are present and get their indices | |
if(length(fields %in% names(first.line)) == length(fields)){ | |
fields.ind = which(names(first.line) %in% fields) | |
} else{ | |
print("The specified fields are not present") | |
} | |
# Create vector to exclude unnecessary columns | |
skip_code = "" | |
for(i in 1:length(names(first.line))){ | |
if(i %in% fields.ind){ | |
skip_code = paste0(skip_code, fields.class[which(names(first.line)[i] == fields)]) | |
} else { | |
skip_code = paste0(skip_code, "_") | |
} | |
} | |
return(read_csv(file, col_types = skip_code, n_max=n_max)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment