将字符串列转换为公式

问题描述 投票:0回答:2

我正在尝试将列中的字符串转换为公式,并根据我指定的值输出结果。例如:

Compo <- c("FE56", "FE58", "FE61", "YI68", "FE11")
Formula <- c("( FE13 / 0.06 ) * CE68", 
             "( ( CE01 + CE02 + CE03 ) / 100 ) * ( 393682 / 10000 )", 
             "FE12 / 0.06", 
             "CE68", 
             "FQ11")
table <- data.frame(Compo, Formula) 

FE13 <- 13
CE68 <- 20
CE01 <- 5
CE02 <- 15
CE03 <- 5.067
FE12 <- 35
FQ11 <-37

table$resultado <- parse(text = tabela$Formula)
table$results <- eval(tabela$resultado)

输出:

但是列

results
只返回最后一个公式的值,而它应该返回每个公式的结果。

r string formula eval
2个回答
1
投票

我建议创建一个向量化和自定义的函数:

parse_string_formula <- function(formula){
  return(eval(parse(text = formula)))
}
parse_string_formula <- Vectorize(parse_string_formula)

table$final_result <- parse_string_formula(table$Formula)

  Compo                                               Formula       final_result
1  FE56                                ( FE13 / 0.06 ) * CE68 4333.3333333333339
2  FE58 ( ( CE01 + CE02 + CE03 ) / 100 ) * ( 393682 / 10000 )    9.8684266940000
3  FE61                                           FE12 / 0.06  583.3333333333334
4  YI68                                                  CE68   20.0000000000000
5  FE11                                                  FQ11   37.0000000000000

1
投票

如果您在数据中设置参数值变量,您也可以使用

dplyr
执行此操作。有时人们建议不要使用
eval()
parse()
组合,所以这里使用了这些相同概念的整洁版本:

library(dplyr)
library(rlang)

Compo <- c("FE56", "FE58", "FE61", "YI68", "FE11")
Formula <- c("( FE13 / 0.06 ) * CE68", "( ( CE01 + CE02 + CE03 ) / 100 ) * ( 393682 / 10000 )", "FE12 / 0.06", "CE68", "FQ11")
table <- data.frame(Compo, Formula) 

params <- data.frame(
  FE13 =  13,
CE68 =  20,
CE01 =  5,
CE02 =  15,
CE03 =  5.067,
FE12 =  35,
FQ11 = 37)

table <- bind_cols(table, params)
table <- table %>% 
  rowwise() %>% 
  mutate(result = eval_tidy(parse_expr(Formula))) %>% 
  select(1,2,result)
table
#> # A tibble: 5 × 3
#> # Rowwise: 
#>   Compo Formula                                                result
#>   <chr> <chr>                                                   <dbl>
#> 1 FE56  ( FE13 / 0.06 ) * CE68                                4333.  
#> 2 FE58  ( ( CE01 + CE02 + CE03 ) / 100 ) * ( 393682 / 10000 )    9.87
#> 3 FE61  FE12 / 0.06                                            583.  
#> 4 YI68  CE68                                                    20   
#> 5 FE11  FQ11                                                    37

创建于 2023-05-18 与 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.