Ignacio
Ignacio

Reputation: 7938

Create new variable that is linear combination of many other variables

Suppose I have a data frame that looks like this:

df1 <- as.data.frame(matrix( rnorm(100*50,mean=0,sd=1), 100, 50))

I want to create a new variable y that is the sum alpha_i*V_i with i from 1 to 50 and where alpha is a random number drawn from a uniform distribution (0,1).

What is the best way of doing this? Can I do it with mutate and dplyr?

Upvotes: 3

Views: 1054

Answers (1)

akrun
akrun

Reputation: 887223

You can try

 df1$newvar <- as.matrix(df1) %*% v1

Or

 df1$newvar <- rowSums(sweep(df1, 2, v1, FUN='*'))

Or as suggested by @Frank based on the post

 df1$newvar <- Reduce(`+`,lapply(seq_along(v1),function(i)df1[[i]]*v1[i]))

data

 set.seed(24)
 df1 <- as.data.frame(matrix( rnorm(100*50,mean=0,sd=1), 100, 50))
 set.seed(48)
 v1 <- runif(50)

 

Upvotes: 3

Related Questions