我有以下代码在R中创建一个数据帧。然后,我创建一个值为零的响应变量y。我希望函数结果从A,B,C和D列的每一行传递值,然后根据d中存储的方程返回存储在y列中的结果。
有人可以帮我吗?
# Create Design Matrix
A <- rep(c(-1, 1), 8)
B <- rep(rep(c(-1, 1), each=2), 4)
C <- rep(rep(c(-1, 1), each=4), 2)
D <- rep(c(-1, 1), each=8)
desMat <- cbind(A,B,C,D)
desMat
y <- 0 #Response Variable
data <- data.frame(desMat,y)
Outcome <- function(w,x,y,z){
#Linear model
set.seed(1456)
e <- rnorm(1,0,3)
d <- 8.3+(5.2*w)-(8.4*x)-(1.8*z)+(7.5*w*z)-(2.1*x*z)+e
return(d)
}
答案 0 :(得分:0)
您可以使用tidyverse中的软件包来做到这一点:
##I converted your matrix to a tibble, but you can always convert back to a matrix by using as.matrix
##Load tidyverse packages
library(tidyverse)
# Create Design Matrix
A <- rep(c(-1, 1), 8)
B <- rep(rep(c(-1, 1), each=2), 4)
C <- rep(rep(c(-1, 1), each=4), 2)
D <- rep(c(-1, 1), each=8)
desMat <- cbind(A,B,C,D)
desMat
y <- 0 #Response Variable
data <- data.frame(desMat,y)
Outcome <- function(w,x,y,z){
#Linear model
set.seed(1456)
e <- rnorm(1,0,3)
d <- 8.3+(5.2*w)-(8.4*x)-(1.8*z)+(7.5*w*z)-(2.1*x*z)+e
return(d)
}
##Then run the following code
desMat_new <- desMat %>% as_tibble() %>% mutate(row_result = Outcome(A, B, C, D))
##if you need the result to be a matrix
desMat_new <- desMat %>% as_tibble() %>% mutate(row_result = Outcome(A, B, C, D)) %>% as.matrix()