-1

I have a data in wide format.e.g.

dt <- (age, gender, income, EDU1990, EDU1991, EDU1992, EDU1993, EDU1994, EDU1995 ..... EDU2021)

I am trying to select all the column with EDU and recode the variables in all of them at once. I tried to use the grep function but it is not working. Example :

grep(^EDU, dt) %>%
  mutate(EDU = recode(^EDU, "highschool"=1, "college"=2)

Is there an easier/better way to select these multiple columns and pipe a function at once?

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
rais
  • 81
  • 6
  • 1
    Welcome to SO, rais! It can be difficult at times trying to help a question when the code is incomplete, usually just trying for "brevity". In this case, it isn't clear if `dt` is a `list` or `data.frame` or similar, nor if you are literally using `grep(^EDU` versus `grep("^EDU"`. Further, `grep` is going to return integers (or `integer(0)`), not a `data.frame` that `dplyr::mutate` expects. Please consider filling out the question a bit to make it self-contained and reproducible with minimal sample data and syntactically correct code. Thanks! – r2evans Aug 03 '21 at 21:01
  • 1
    Some links that provide good discussion and examples of how to do that include: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Aug 03 '21 at 21:01
  • 1
    @r2evans Thank you for the welcome. I just started here so I will make sure I will try harder to better frame my question next time :) – rais Aug 04 '21 at 21:10
  • @r2evans I just tried to frame my question better here - https://stackoverflow.com/questions/68672373/selecting-large-number-of-columns-for-recoding-the-variable-values . Thank you for the comments and guidance ! – rais Aug 05 '21 at 19:18

1 Answers1

1

We can use dplyr

library(dplyr)
dt %>%
    mutate(across(starts_with('EDU'),  ~recode(., "highschool"=1, "college"=2)))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you akrun. It did not work and I think it might be because I did not frame my question correctly. Here is my 2nd attempt to frame my question - https://stackoverflow.com/questions/68672373/selecting-large-number-of-columns-for-recoding-the-variable-values Your help would be appreciated ! – rais Aug 05 '21 at 19:17