I'm trying to convert a character variable into a logical expression in order to use it later inside the subset argument of the subset() function, and all of this is inside a bigger function called early_prep() I created. The problem is when I execute

early_prep(file_name = "n44.txt", keep_rows = "block > 1")

it deletes all rows in my raw_data data frame instead of deleting only those in which block > 1.

Bellow is the relevant part of the early_prep() function:

early_prep <- function(file_name,keep_rows = FALSE){

  read_data <- function(file_name){
  extension <- substr(file_name, nchar(file_name) - 3, nchar(file_name))
  if (extension == ".txt"){
    raw_data <<- read.table(file_name, header = TRUE)
    # Print to console
    print("#### Reading txt file ####", quote = FALSE)
  } else if (extension == ".csv"){
    raw_data <<- read.csv(file_name, header = TRUE)
    # Print to console 
    print("#### Reading csv file ####", quote = FALSE)
  } else {
    # Stops running the function
    stop("#### file_name should end with txt or csv extension ####", quote = FALSE)     
  }
 }


  read_data(file_name)

  if (keep_rows != FALSE) {
   keep_rows <- as.logical(keep_rows)
   raw_data <<- subset(raw_data,  keep_rows)
   # Print to console
   print("#### Deleting unnecessary rows in raw_data ####", quote = FALSE)
  }
}  
1

There are 1 answers

6
agstudy On BEST ANSWER

Try this :

subset(raw_data,eval(parse(text=keep_rows)))

Test :

keep_rows <- "Blok>1"
raw_data<- data.frame(Blok=c(1,2,3,0))
subset(raw_data,eval(parse(text=keep_rows)))

  Blok
2    2
3    3