Home > Net >  as.numeric() as a for loop possible?
as.numeric() as a for loop possible?

Time:09-29

I was curious to see if there is a way to craft a for loop to do apply as.numeric() for a certain columns, since the entire DF is considered to be as a character. Perhaps I have a very large data set, and I want to make a certain column, until the very last column, to be applied.

I looked into lapply, but I think I am more confused on that.

DF =

Person KLAS XDXS ASDD BBHS JKJA
First Meyer 33 22 21 12
Second Walmart 34 23 28 19
Third Safeway 35 29 21 11
Fourth ... ... ... ... ...

Is there a way to make a for loop where I can do as.numeric() for each column, say starting at column 3 and until the very end? I would be working with large data sets, so I was wondering if there was a way to do that. Cause I dont think I can do as.numeric when there are actual characters in column 1 and 2, and using unlist() makes the problem worse.

Person <- c("First", "Second", "Third", "Fourth")
KLAS <- c("Meyer", "Walmart", "Safeway", "Kroger")
XDXS <- c("33", "34", "35", "22")
ASDD <- c("21", "28", "21", "11")
BBHS <- c("22", "23", "21", "18")
JKJA <- c("12", "19", "11", "8")
DF <- data.frame(Person, KLAS, XDXS, ASDD, BBHS, JKJA)

CodePudding user response:

You can slice only the columns you want and use apply with 2 as the second argument to apply a function along each column:

DF[, 3:ncol(DF)] <- apply(DF[, 3:ncol(DF)], 2, as.numeric)

CodePudding user response:

You could look into this similar question

See below code adapted from one of the answer. You can design a function to check if you can convert the column (otherwise as.numeric() will introduce NAs) and then transform your data:

library(dplyr)

is_all_numeric <- function(x) {
  !any(is.na(suppressWarnings(as.numeric(na.omit(x))))) & is.character(x)
}

DF %>%  mutate_if(is_all_numeric,as.numeric)

  Person    KLAS XDXS ASDD BBHS JKJA
1  First   Meyer   33   21   22   12
2 Second Walmart   34   28   23   19
3  Third Safeway   35   21   21   11
4 Fourth  Kroger   22   11   18    8

'data.frame':   4 obs. of  6 variables:
 $ Person: chr  "First" "Second" "Third" "Fourth"
 $ KLAS  : chr  "Meyer" "Walmart" "Safeway" "Kroger"
 $ XDXS  : num  33 34 35 22
 $ ASDD  : num  21 28 21 11
 $ BBHS  : num  22 23 21 18
 $ JKJA  : num  12 19 11 8
  • Related