在数据框中调用 运行 model/equation

Call and run model/equation when in a data frame

根据下面显示的数据框,我想运行 'struct' 列中的公式。基本上,我需要一个将 'struct' 列中的方程式视为代码的 R 函数。非常欢迎任何想法!

x <- runif(60, min = 2, max = 35)
y <- runif(60, min = 0, max = 10)
z <- runif(60, min = 5, max = 20)
struct1 <- rep("x + y + z", times = 20)
struct2 <- rep("x - y - z", times = 20)
struct3 <- rep("x * y * z", times = 20)
struct <- c(struct1, struct2, struct3)
dd <- data.frame(x, y, z, struct)
rm(x, y, z, struct, struct1, struct2, struct3)

不是很优雅,但有效:

set.seed(1)
library(data.table)
x <- runif(60, min = 2, max = 35)
y <- runif(60, min = 0, max = 10)
z <- runif(60, min = 5, max = 20)
struct1 <- rep("x + y + z", times = 20)
struct2 <- rep("x - y - z", times = 20)
struct3 <- rep("x * y * z", times = 20)

struct <- c(struct1, struct2, struct3)
struct_1<-paste("function(x,y,z){",struct,"}",sep="")
struct_2<-paste(paste("func_",seq(1:length(struct)),"<-",sep=""),sep="")
struct<-paste(struct_2,struct_1,sep="")
struct<-paste(struct,
              paste(gsub("<-","",struct_2),"(x,y,z)",sep=""),sep="\n ")
dd <- data.frame(x, y, z, struct)
rm(x, y, z, struct, struct1, struct2, struct3)
dd<-as.data.table(dd)
dd[,needed_var:=eval(parse(text=as.character(struct))),by=1:nrow(dd)]

这一行代码将计算结构中相应的公式并将结果存储在dd$result

x <- runif(60, min = 2, max = 35)
y <- runif(60, min = 0, max = 10)
z <- runif(60, min = 5, max = 20)
struct1 <- rep("x + y + z", times = 20)
struct2 <- rep("x - y - z", times = 20)
struct3 <- rep("x * y * z", times = 20)
struct <- c(struct1, struct2, struct3)
dd <- data.frame(x, y, z, struct, stringsAsFactors = FALSE)
rm(x, y, z, struct, struct1, struct2, struct3)

dd$result <- sapply(1:nrow(dd), function(i) with(dd[i,], eval(parse(text = struct))))