Tiffany
Tiffany

Reputation: 301

Remove quotes when using assign function in R

I'm trying to read in output from another program into R. The data I'm reading in comes in as a line with the variable name preceded by the # sign (e.g., #var1) followed by another line of the values, followed by a variable name, followed by values, etc. I'm trying to read the input file and parse out the variables with the values associated. Some variables are scalars, while others are vectors. The problem I'm running into is when I use the assign function it puts quotes around my variable names as well as the values. If the values are a vector then there are quotes surrounding the entire vector, not individual values. I have tried using the noquote function inside my for loop, but the output still has quotes. Any ideas how to remove these quotes within the looping structure?

thank you!

f <- scan(fname,what=character(),sep = "\n", quiet =TRUE,blank.lines.skip=F)
length(f)

varname_idx <- seq(1,length(f),2)
values_idx <- seq(2,length(f),2)

varname <- list()
values <- list()

for(i in 1:length(varname_idx)){
   varname[i]<-substr(f[[varname_idx[i]]],2,20)
   values[i]<- f[[values_idx[i]]]       

 assign(varname[[i]][1], values[[i]])  
}

Some additional info - f looks like this:

[1] "#var1"
[2] "0.3009"
[3] "#var2"
[4] "1 13 24 5 6 12"
...

Upvotes: 2

Views: 1175

Answers (1)

Carlos Cinelli
Carlos Cinelli

Reputation: 11607

If your values are separated by spaces, you could split them by spaces, unlist and transform to numeric. Something like this should work (it works in your sample of the f data ):

for(i in 1:length(varname_idx)){
  varname[i]<-substr(f[[varname_idx[i]]],2,20)
  values[[i]]<- as.numeric(unlist(strsplit(f[[values_idx[i]]], " ")))

  assign(varname[[i]][1], values[[i]])  
}

Upvotes: 1

Related Questions