Skip to content

Instantly share code, notes, and snippets.

@fipar
Last active January 21, 2016 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fipar/3e4e266752bac607d05b to your computer and use it in GitHub Desktop.
Save fipar/3e4e266752bac607d05b to your computer and use it in GitHub Desktop.
Importing a csv file with math expressions into R, evaluating them into the results
# To get from:
# telecaster:data_collection_scripts fernandoipar$ cat /tmp/test.csv
# 1*1,0,1
# 1*2,0,2
# 2+4,1*1024*1024,2*1024*1024*1024
# to:
# > t
# V1 V2 V3
# 1 1 0 1
# 2 2 0 2
# 3 6 1048576 2147483648
t <- read.csv("/tmp/test.csv",header=F,stringsAsFactors=F)
for (row in 1:nrow(t)) {
for (col in 1:ncol(t)) {
t[col,row] <- eval(parse(text=as.character(t[col,row])))
}
}
# The problem here is that date/time fields will be interpreted as intervals, so if
# importing a csv with such fields (as is the case of my original goal here, to import
# mongostat output into R) this is needed:
mongostat <- read.csv("/tmp/mongostat.csv",header=T,stringsAsFactors=F)
for (row in 1:nrow(mongostat)) {
for (col in 1:ncol(mongostat)) {
if (length(grep("[0-9][0-9]:[0-9][0-9]", mongostat[row,col])) == 0) {
mongostat[row,col] <- eval(parse(text=as.character(mongostat[row,col])))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment