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
Asked
Active
Viewed 673 times
0

bricevk
- 197
- 8
-
1What 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 <- list("var1", "var2") data[stringvars] = lapply(data[stringvars], as.numeric) ``` I don't think that works? Ideally, I could simply tell the people who use this code "fill in the variables on the list command, and then run this command to destring everything within the list. – 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 <- c("var1", "var2")` it will work just fine. [I'm a big fan of lists](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207), but don't use lists when vectors will do. – 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 <- 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