Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a column by finding its corresponding value in a colname

My problem is pretty similar to the following post

In my database i have multiple columns containing values like M0, M6, M12… and so on. And i have columns having those names M0, M6, M12…

I would like to replace the first columns containing the M0… with the value corresponding in the column

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As an understanding example i have :

df <- data.frame(time=c("M0","M12","M0","M0","M12"),
                 M0=c(1,2,4,5,1),
                 M12=c(8,5,9,2,1))
df
  time M0 M12
1   M0  1   8
2  M12  2   5
3   M0  4   9
4   M0  5   2
5  M12  1   1

As mentioned i found a post with interesting answers, and one in particular with the use of cur_data()

df2 <- df %>%
  rowwise %>%
  mutate(newd = cur_data()[[cur_data()$time]]) %>%
  ungroup 
df2
# A tibble: 5 × 4
  time     M0   M12  newd
  <chr> <dbl> <dbl> <dbl>
1 M0        1     8     1
2 M12       2     5     5
3 M0        4     9     4
4 M0        5     2     5
5 M12       1     1     1

It works, but takes a really long time and also apparently the cur_data is deprecated in favor of pick() which i don’t get how to replace to make it work

Any advice on this would be much appreciated !

>Solution :

rowwise is a pretty slow operation in dplyr, even for moderately sized data frames. One possibility is to iterate in parallel over time and the row number and simply select the value:

library(dplyr)
library(purrr)

df |>
  mutate(newd = map2_dbl(row_number(), time, \(idx, var) df[idx, var]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading