Home > Software design >  Returning the name of column based on the value of another column
Returning the name of column based on the value of another column

Time:09-19

I have a dataset as follow :

A <- rnorm(5)
B <- rnorm(5)
C <- rnorm(5)
D <-c(1,3,2,2,1)

data_ex <-data.frame(A,B,C,D)

And I would like to get the name of the column corresponding to the value of the column D. The goal is then to create a new column (E) with the values corresponding.

If data_ex$D[1]=1 then data_ex$E will take the value of column A, as it is the 1 st one

Does anyone have an idea on how to do it?

Thanks!

CodePudding user response:

You can use imap_chr:

library(purrr)
library(dplyr)
data_ex %>% 
  mutate(E = imap_chr(D, ~ data_ex[.y, .x]))

output

       A       B      C     D      E
   <dbl>   <dbl>  <dbl> <dbl>  <dbl>
1 1.63   -0.742  -0.185     1  1.63 
2 0.227  -0.0463 -0.289     3 -0.289
3 0.0584  2.40   -0.775     2  2.40 
4 1.17   -0.546   1.22      2 -0.546
5 0.940  -0.428   0.847     1  0.940

Another option using get:

data_ex %>% 
  rowwise() %>% 
  mutate(E = get(colnames(data_ex)[D]))

CodePudding user response:

You could index the data by [ a matrix with 2 columns.

data_ex$E <- data_ex[cbind(1:nrow(data_ex), data_ex$D)]
data_ex

           A          B          C D          E
1  0.7514365  0.8812175 -0.3433850 1  0.7514365
2  0.7100048  0.6242513  0.1433020 3  0.1433020
3 -1.1886939 -0.9786522 -0.8433015 2 -0.9786522
4 -2.4183947 -0.9422634  0.8168351 2 -0.9422634
5 -0.3896213 -0.2279482 -0.6598410 1 -0.3896213

Its dplyr equivalent:

library(dplyr)

data_ex %>%
  mutate(E = .[cbind(1:n(), D)])
  • Related