Replace matrix values based on vector with matching names in R

I have a data frame in R with binary entries for three variables (a, b and c)

set.seed(12)
library(dplyr)
df <- data.frame(a = rbinom(10, 1, 0.5), b = rbinom(10, 2, 0.3), c = rbinom(10, 1, 0.8))

df
a b c
1  0 1 1
2  1 1 0
3  0 0 1
4  1 1 1
5  0 0 1
6  1 1 1
7  1 0 1
8  0 0 1
9  0 1 1
10 1 0 1

I also have a numeric vector whose names are the same of the columns in df:

vec <- rnorm(3, 1, 0.5)
names(vec) <- colnames(df)
vec

       a         b         c 
1.3369906 2.0360179 0.7294857

Here's the thing: for each column in df and for each observation, if the variable has a value of 1, then replace the 1 by the values in vec. Otherwise, if the original value is 0, then I want to keep it. I tried to perform a loop, but it didn't work well.

for(i in 1:ncol(df)){

  df[,i][df==1] <- vec[i]

} 

I feel it might be due to the need to specify the matching pattern between the matrix and the vector. Is there an alternative way to do that?

Upvotes: 0

Views: 395

Answers (1)

Tanner33
Tanner33

Reputation: 140

If you want to use a loop, the following should do the trick.

for(i in 1:ncol(df)){
  for(j in 1:nrow(df)){
    if(df[j,i]>=1){df[j,i]<-vec[colnames(df[i])]}
    else{df[j,i]<-df[j,i]}
  }
}

Upvotes: 1

Related Questions