Replacing row values ​​by column name in R

I have a data frame 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 am trying to replace row values ​​when this row column name is equal to the value in column Z. Desired result 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 thought something like the following code applied to each line

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

But I can’t understand. Any help appreciated

Hooray!

+4
source share
2 answers

Matrix indexing match- casting a column ztocolnames

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
+2
source

This will only work if the columns with letters are in lexicographic 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
+1
source

Source: https://habr.com/ru/post/1568238/


All Articles