Search code examples
renvironment-variablesassigndo.call

Read in a file and set fields as variables in R


I am trying to read in a file and have R set each data pair as an environmental variable.

I have an input file that comes from the web with the data below. It has both numeric and character variables that need to be read in. This is where I am getting hung up, as I can only seem to bring them in as one or the other, which makes assign, or do.call error out when it hits characters that are classified as numeric, or vice versa.

Any ideas?

input file "input":
user <- "johndoe", date <- "1-30-2019", run <- 1, scoring <- "default", 
high_cutoff <- 70, low_cutoff <- 15, bg1 <- 12, bg2 <- 12, bg3 <- 12, 
group_cut <- 60, stbg <- "no", factor <- 25, rest <- 2, 
loo_enable <- "no"

wd <- getwd() 
phpvars <- as.data.frame(t(read.table(paste0(wd, "/input"), sep = ",")))


#attempt 1 - reads everything in as character
for (i in phpvars$V1){
 x<- t(as.data.frame(strsplit(i," <- ")))
 assign(x[1,1],(x[1,2]))
}

#attempt 2 - tries to detect type of each data point as it comes in, and 
#assign as. (numeric or character)

for (i in phpvars$V1){
 x<- t(as.data.frame(strsplit(i," <- ")))
 type <- typeof(x[1,2])
 d <- paste0("as.", type)
 e <- x[1,2]
 assign(x[1,1],paste(d,(e)))
 }



#alternate to assign - has same problems though
do.call("<-",list(x[1,1],x[1,2]))

Desired Output as environmental variables:

 user <- "johndoe"
 date <- "1-30-2019"
 run <- 1
 scoring <- "default"
 high_cutoff <- 70
 low_cutoff <- 15
 bg1 <- 12
 bg2 <- 12
 bg3 <- 12
 group_cut <- 60
 stbg <- "no"
 factor <- 25
 rest <- 2
 loo_enable <- "no"

Is there a way (better way) to read in data and set them as environmental variables?


Solution

  • You already have a great quoted input. Take advantage of that by specifying that your input string is quoted with quote = "" argument upon using read.table() function:

    wd <- getwd() 
    phpvars <- as.data.frame( t( read.table( paste0(wd, "/input") ,
                                             sep = ",",   
                                             quote = "" ) ) )
    

    Then you just have to parse each row of phpvars table and evaluated them by using parse() and eval() functions respectively:

     for(i in phpvars$V1){
    
         eval( parse( text = as.character(i) ) )
     }