将字符变量转换为逻辑表达式,以便稍后在 subset() 函数的子集参数中使用它
Convert a character variable into a logical expression in order to use it later inside the subset argument of the subset() function
我正在尝试将字符变量转换为逻辑表达式,以便稍后在 subset() 函数的子集参数中使用它,所有这些都在一个更大的函数中,称为 early_prep () 我创建。问题是当我执行
early_prep(file_name = "n44.txt", keep_rows = "block > 1")
它会删除我的 raw_data 数据框中的所有行,而不是仅删除块 > 1 中的行。
波纹管是 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)
}
}
试试这个:
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
我正在尝试将字符变量转换为逻辑表达式,以便稍后在 subset() 函数的子集参数中使用它,所有这些都在一个更大的函数中,称为 early_prep () 我创建。问题是当我执行
early_prep(file_name = "n44.txt", keep_rows = "block > 1")
它会删除我的 raw_data 数据框中的所有行,而不是仅删除块 > 1 中的行。
波纹管是 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)
}
}
试试这个:
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