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

Conditionally take value from column1 if the column1 name == first(value) from column2 BY GROUP

I have this fake dataframe:

df <- structure(list(Group = c(1L, 1L, 2L, 2L), A = 1:4, B = 5:8, C = 9:12, 
X = c("A", "A", "B", "B")), class = "data.frame", row.names = c(NA, -4L))

  Group A B  C X
1     1 1 5  9 A
2     1 2 6 10 A
3     2 3 7 11 B
4     2 4 8 12 B

I try to mutate a new column, which should take the value of THE column that has the column name in an other column:

Desired output:

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

Group   A   B   C   X new_col
1       1   5   9     A 1
1       2   6   10    A 1
2       3   7   11    B 7
2       4   8   12    B 7

My try so far:

library(dplyr)

df %>% 
  group_by(Group) %>% 
  mutate(across(c(A,B,C), ~ifelse(first(X) %in% colnames(.), first(.), .), .names = "new_{.col}"))

  Group     A     B     C X     new_A new_B new_C
  <int> <int> <int> <int> <chr> <int> <int> <int>
1     1     1     5     9 A         1     5     9
2     1     2     6    10 A         1     5     9
3     2     3     7    11 B         3     7    11
4     2     4     8    12 B         3     7    11

>Solution :

One option might be:

df %>%
    rowwise() %>%
    mutate(new_col = get(X)) %>%
    group_by(Group, X) %>%
    mutate(new_col = first(new_col))

 Group     A     B     C X     new_col
  <int> <int> <int> <int> <chr>   <int>
1     1     1     5     9 A           1
2     1     2     6    10 A           1
3     2     3     7    11 B           7
4     2     4     8    12 B           7
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