1

I would like to convert a character vector within a dataframe of a list into a numeric one. I have an example attached. Data at the end looks like my list I import directly into R and in which I want to convert character into numeric...

set.seed(94756)

mat1 <- matrix(sample(seq(-1,100, 0.11),50, replace = TRUE),ncol = 5) 
mat1 <- as.data.frame(mat1)
mat1$V2 <- as.character(mat1$V2)

mat2 <- matrix(sample(seq(-1,100, 0.11),50, replace = TRUE),ncol = 5)  
mat2 <- as.data.frame(mat2)
mat2$V2 <- as.character(mat2$V2)

mat3 <- matrix(sample(seq(-1,100, 0.11), 50,replace = TRUE),ncol = 5)  
mat3 <- as.data.frame(mat2)
mat3$V2 <- as.character(mat3$V2)

data <- list(mat1, mat2, mat3)

Thanks in advance!

timtams
  • 101
  • 6

1 Answers1

1

type.convert can change column types in list as well (assuming those columns within the data.frame doesn't have any non-numeric element in it)

data <- type.convert(data, as.is = TRUE)

-output

> str(data)
List of 3
 $ :'data.frame':   10 obs. of  5 variables:
  ..$ V1: num [1:10] 46.08 10.55 36.62 46.52 5.38 ...
  ..$ V2: num [1:10] 47.2 12.9 38.7 53 84.1 ...
  ..$ V3: num [1:10] 81.9 58.3 75 56.8 57.9 ...
  ..$ V4: num [1:10] 60.5 52.2 77 55.6 95.4 ...
  ..$ V5: num [1:10] 96.5 40.7 58.7 28.3 16.7 ...
 $ :'data.frame':   10 obs. of  5 variables:
  ..$ V1: num [1:10] 14.1 20.9 32.5 91.7 58.7 ...
  ..$ V2: num [1:10] 47.4 48.9 63.1 48 72 ...
  ..$ V3: num [1:10] 61.6 21 56.5 88 53.2 ...
  ..$ V4: num [1:10] 56.86 -0.01 12.86 33.32 55.32 ...
  ..$ V5: num [1:10] 73.58 9.12 57.96 10.88 86.78 ...
 $ :'data.frame':   10 obs. of  5 variables:
  ..$ V1: num [1:10] 14.1 20.9 32.5 91.7 58.7 ...
  ..$ V2: num [1:10] 47.4 48.9 63.1 48 72 ...
  ..$ V3: num [1:10] 61.6 21 56.5 88 53.2 ...
  ..$ V4: num [1:10] 56.86 -0.01 12.86 33.32 55.32 ...
  ..$ V5: num [1:10] 73.58 9.12 57.96 10.88 86.78 ...
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Why does `lapply(data, function(x) as.numeric(as.character(x)))` does not work here? – TarJae Mar 02 '22 at 21:51
  • Unfortunately the result is NA only, I don't know why... – timtams Mar 03 '22 at 08:53
  • I guess I have to start at the beginning. I read in files into R. Those files have numbers with commas as separator for decimal numbers. So at first I have to solve that problem. After that this code will work probably. But for now it doesn't... – timtams Mar 03 '22 at 09:02
  • @TarJae you need nested `lapply` i.e. `lapply(data, function(x) {x[] <- lapply(x, as.numeric); x})` because as.numeric/as.character works on vectors and the `data` is ` list` o fdata.frames – akrun Mar 03 '22 at 15:27
  • @timtams this works only when you have some data.frame/vectors which are wrongly typed as `character` when they should be otherwise numeric. If you have a column with `c('hello', 1, 2, 3)` it wouldn't work because the first element is not numeric where as `c('1', '2', '3')` will get converted to numeric – akrun Mar 03 '22 at 15:28