简体   繁体   English

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

[英]Applying function to each row in dataframe and storing result in new column

I have the following code to create a dataframe in R. I then create a response variable y with values of zero. 我有以下代码在R中创建一个数据帧。然后创建一个值为零的响应变量y。 I would like the function outcome to be passed values from each row in columns A,B,C,and D and then return the resulting outcome stored in column y according to the equation stored in d. 我希望函数结果从A,B,C和D列的每一行传递值,然后根据d中存储的方程返回存储在y列中的结果。

Can anyone help me out here? 有人可以帮我从这里出去吗?

# 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)
}

You can use the packages in tidyverse to do that: 您可以使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM