2017-05-28 1 views
0

以下に示すデータフレームに基づいて、 '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) 

答えて

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

これは奇妙なことですが、私は新しいセッションでそれをreranして動作します(data.tableライブラリをロードしましたか? – Vitalijs

+0

はい、私はdata.tableをインストールしていませんでした! – user3262756

1

この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)))) 
関連する問題