-3

I am trying to set some variables as character and others as numeric, what I currently have is;

colschar <- c(1:2, 68:72)    
colsnum <- c(3:67) 
subset <- as.data.frame(lapply(data[, colschar], as.character), (data[, colsnum], as.numeric))

which returns an error. I am trying to set columns 1:2 and 68:72 as a character and columns 3:67 all as numeric.

user113156
  • 6,761
  • 5
  • 35
  • 81
  • 3
    You forgot the second `lapply`. – Vincent Jan 03 '18 at 16:02
  • I originally tried with two `lapply`´s but get the following error; `Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : row names supplied are of the wrong length` – user113156 Jan 03 '18 at 16:05
  • 2
    It would be easier to help you if you provided some sort of [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). How did all the data types become incorrect in the first place? Did you not import the data correctly? Show the exact code that gives you that error. – MrFlick Jan 03 '18 at 16:09
  • 1
    Then edit your question with the original code and this error. – Vincent Jan 03 '18 at 16:09

2 Answers2

5

I suggest:

data[colschar] <- lapply(data[colschar], as.character)
data[colsnum] <- lapply(data[colsnum], as.numeric)
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 3
    What? No. This is far too simple and readable. Can't you do it in one expression split across several lines of code, using pipes and at least 2 external packages? – Gregor Thomas Jan 03 '18 at 16:15
2

It should be better if you share an extract of your data. In any case you may try with tidiverse approach:

library(dplyr)
mydf_molt <- mydf %>% 
    mutate_at(.vars=c(1:2, 68:72),.funs=funs(as.character(.))) %>% 
    mutate_at(.vars=c(3:67),.funs=funs(as.numeric(.)))
Scipione Sarlo
  • 1,470
  • 1
  • 17
  • 31
  • 3
    Though a reasonable answer, I suggest you not load all of the `"tidyverse"` here; please include only those libraries that are required for this answer (`dplyr` for this, I believe). – r2evans Jan 03 '18 at 16:15
  • It is reasonable what you said. Usually I also use other functions that are developed in `tidyverse` approach when I make data wrangling, it's an habit (maybe bad) loading the whole package for me. – Scipione Sarlo Jan 03 '18 at 16:19
  • 2
    I agree that there are many useful functions, and it's easy to do that ... unfortunately, for those that are less-familiar with the packages, it can also be waaaaaaaaay overkill to load all of them. Not to mention the dependency hell if they need to install any of the lesser-used tidyverse (`broom`, `dbplyr`, `rvest`, perhaps `ggplot2` ... the list of loaded packages [is quite long](https://cran.r-project.org/web/packages/tidyverse/index.html).) – r2evans Jan 03 '18 at 16:22