0

I am trying to write some code in R for others to use who are in the field at my company. I need a generic code where they can create a list of variables within a dataset that are stored as strings, and then run a command to destring all variables in that list at once. I know how I would do this using the TaRifx package, but I'm not sure how to make this code as generic and user-friendly as possible

bricevk
  • 13
  • 4
  • 1
    What does "restring all variables" mean to you? Can you give a small example with input and desired output? – Gregor Thomas Apr 12 '21 at 14:26
  • sorry, "destring" - I'll correct that typo. restring means nothing to me but destring means making values numeric (as you know) – bricevk Apr 12 '21 at 14:28
  • `data[cols] = lapply(data[cols], as.numeric)` – Gregor Thomas Apr 12 '21 at 14:30
  • Thats helpful, but can I put a list of variables into this command? ```stringvars – bricevk Apr 12 '21 at 14:35
  • Why would you use a `list` instead of a character vector for column names? If you use `stringvars – Gregor Thomas Apr 12 '21 at 14:38
  • If you really need a list, you can just `unlist` it first, `data[unlist(stringvars)] = lapply(data[unlist(stringvars)], as.numeric)`. That will work with lists or character vectors, assuming the list is reducible to a character vector by `unlist()`... – Gregor Thomas Apr 12 '21 at 14:40
  • You could also use `dplyr`, which is often easier to introduce new people to than base R, e.g., `data % mutate(across(all_of(stringvars), as.numeric))`. It will also expect a character vector, so use `unlist()` if you insist on lists. – Gregor Thomas Apr 12 '21 at 14:42
  • You're totally right. Been in stata lately rather than R, and in stata, a "varlist" of variables acts like a vector in R. thanks for helping me knock some rust off. – bricevk Apr 12 '21 at 14:45

0 Answers0