简体   繁体   中英

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. 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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