2017-05-28 78 views
0

根據下面顯示的數據框,我想運行「struct」列中的公式。基本上,我需要一個R函數來處理'struct'列中的方程作爲代碼。任何想法非常歡迎!在數據框中調用並運行模型/公式

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) 

回答

1

不是很優雅,但工程:

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)] 
+0

非常感謝您的回覆。但是,代碼似乎不適用於我,您是否可以查看是否有錯誤? – user3262756

+0

這很奇怪,我剛剛在一個新的會話中重新運行它並且工作(您是否加載data.table庫? – Vitalijs

+0

是的,我沒有注意到我沒有安裝data.table!它的工作,非常感謝! – user3262756

1

這一個行代碼將評估在結構中的相應的公式和結果存儲在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)))) 
相關問題