将函数应用于数据帧中的每一行并将结果存储在新列中



我有以下代码在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)
}

您可以使用 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()

最新更新