我正在尝试将字符变量转换为逻辑表达式,以便稍后在subset()函数的子集参数中使用它,所有这些都在我创建的名为early_prep()的更大函数内部。问题是当我执行
时early_prep(file_name = "n44.txt", keep_rows = "block > 1")
它会删除raw_data数据框中的所有行,而不是仅删除其中的块> 1。
Bellow是early_prep()
函数的相关部分:
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)
}
}
答案 0 :(得分:1)
试试这个:
subset(raw_data,eval(parse(text=keep_rows)))
测试:
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