我有一個帶有資料的資料框和一個帶有邏輯規則dat的向量rule
set.seed(124)
ro <- round(runif(n = 30,1,10),2)
dat <- as.data.frame(matrix(data =ro,ncol = 3)) ; colnames(dat) <- paste0("x" ,1:ncol(dat))
rule <- c("x1 > 5 & x2/2 > 2" , "x1 > x2*2" , "x3!=4")
我需要檢查運算式是否為真
id <- 2
for(i in 1:nrow(dat)){
cr <- with(data = dat[i,] , expr = eval(parse(text = rule[id])))
print(cr)
}
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] TRUE
[1] FALSE
[1] FALSE
[1] FALSE
[1] TRUE
如何做到這一點Rcpp?
uj5u.com熱心網友回復:
這里值得強調的兩件事是
你不需要所有行都低,因為 R 是矢量化的,而且已經很快了
您可以掃描資料的規則并回傳結果矩陣
這兩個都是單行的:
> res <- do.call(cbind, lapply(rule, \(r) with(dat, eval(parse(text=r)))))
> res
[,1] [,2] [,3]
[1,] FALSE FALSE TRUE
[2,] FALSE FALSE TRUE
[3,] TRUE FALSE TRUE
[4,] FALSE FALSE TRUE
[5,] FALSE FALSE TRUE
[6,] FALSE TRUE TRUE
[7,] TRUE FALSE TRUE
[8,] TRUE FALSE TRUE
[9,] TRUE FALSE TRUE
[10,] FALSE TRUE TRUE
>
(我在那里使用了 R 4.1.* 匿名函式,您也可以\(r)使用標準function(r)。)
由于這已經矢量化,它將比您的每行呼叫更快,即使您使用 Rcpp 執行它,也不會比已經矢量化的代碼(多)快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457299.html
