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!
CodePudding user response:
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 ...