EN VI

Creating a column by finding its corresponding value in a colname?

2024-03-15 23:00:04
How to 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

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]))
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login