complex question with rowwise and mutate

the data

id total_years  total_love_years total_years30 total_love_years30 first_match true_value true_love_value
1      18          282               373              1991         total_years    18          282
2
3
4

essentially I want to create the latter two columns "true_value" and "true_love_value" based on the column name in "first_match". in creating the "true_value" column, I look at the "first_match" column. it says "total_years",hence I am taking the value in "total_years". similarly, for "true_love_value" column I am taking the value in "total_love_years", as the first_match column is for "total_years" and not "total_years30". I think I know how to make the first column. making the second column is now the difficult part you seen.

my code is using the tidy verse and is follows:

data %>% 
rowwise() %>% 
mutate(true_value = cur_data()[[first_match]])

again, I want to make mutate create me a new column titled "true_love_value" that gives me the value in "total_love_years" column.. I select the value from "total_love_years", as the "first_match" column directs me to do so.

is there a way to do this with paste0 maybe. I have a several different columns I want to do this for, so i want to avoid a case_when. this data is a much more simplified version but illustrates the issue

thank u

I think this basically does what you want:

data <- data.frame(
  id = 1,
  total_years = 18,
  total_love_years = 282,
  total_years30 = 373,
  total_love_years30 = 1991,
  first_match = 'total_years'
)

library(tidyverse)
data |>
  pivot_longer(cols = total_years:total_love_years30,
               names_to = 'relevant_cols', values_to = 'true_value') |>
  filter(first_match == relevant_cols | first_match == str_remove(relevant_cols,'_love'))
#> # A tibble: 2 × 4
#>      id first_match relevant_cols    true_value
#>   <dbl> <chr>       <chr>                 <dbl>
#> 1     1 total_years total_years              18
#> 2     1 total_years total_love_years        282

Created on 2022-09-01 by the reprex package (v2.0.1)

This will only keep the entry in true_value if the condition is met, but it relies on the names you used in your example data. In general, try to use a long format for your data instead of the wide one, it will make the most of your work a lot easier.

Kind regards

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.