Arc121
Arc121

Reputation: 43

Replacing row values by column name in R

I have a data frame as below

df<- data.frame(a = c(1,2,3,4,5), 
                b = c(6,7,8,9,10), 
                c = c(11,12,13,14,15), 
                z = c("b","c","a","a","b"))

I'm trying to replace row values where that row's column name is equal to the value in column Z. The desired output is below

   a  b  c z
1  1 NA 11 b
2  2  7 NA c
3 NA  8 13 a
4 NA  9 14 a
5  5 NA 15 b

I was thinking something like the following code applied to each row

If column name is equal to Z, replace value with NA

But can't figure it out. Any help appreciated

Cheers!

Upvotes: 4

Views: 1242

Answers (2)

thelatemail
thelatemail

Reputation: 93813

Matrix indexing match-ing the z column to the colnames

df[cbind(seq(nrow(df)),match(df$z,colnames(df[1:3])))] <- NA
df

   a  b  c z
1  1 NA 11 b
2  2  7 NA c
3 NA  8 13 a
4 NA  9 14 a
5  5 NA 15 b

Upvotes: 2

IRTFM
IRTFM

Reputation: 263301

This is only going to work if the columns with the letters are in lexigraphic order:

> df[cbind(1:5,as.numeric(df$z))] <- rep(NA,5)
> df
   a  b  c z
1  1 NA 11 b
2  2  7 NA c
3 NA  8 13 a
4 NA  9 14 a
5  5 NA 15 b

Upvotes: 1

Related Questions