Home > Software engineering >  Convert the columns in each element of a list to strings
Convert the columns in each element of a list to strings

Time:12-16

Let's say I have a list of 3 elements x, y and z. The cols in each of these lists are of type double. Is there a quick way to convert the all the cols to strings?

dput(mylist)
list(structure(list(Age = c(1L, 1L, 2L, 3L, 4L, 5L), Year = c(10L, 
11L, 10L, 11L, 10L, 12L)), class = "data.frame", row.names = c(NA, 
-6L)), structure(list(Age = c(1L, 1L, 2L, 3L, 4L, 5L), Year = c(12L, 
14L, 10L, 11L, 5L, 12L)), class = "data.frame", row.names = c(NA, 
-6L)), structure(list(Age = c(1L, 1L, 2L, 3L, 4L, 5L), Year = c(12L, 
14L, 10L, 11L, 5L, 12L)), class = "data.frame", row.names = c(NA, 
-6L)))

I've tried various ways with lapply but just can't get it right.

CodePudding user response:

You can try rapply

res <- rapply(
  mylist,
  as.character,
  how = "replace"
)

and you will see

> res
[[1]]
  Age Year
1   1   10
2   1   11
3   2   10
4   3   11
5   4   10
6   5   12

[[2]]
  Age Year
1   1   12
2   1   14
3   2   10
4   3   11
5   4    5
6   5   12

[[3]]
  Age Year
1   1   12
2   1   14
3   2   10
4   3   11
5   4    5
6   5   12

> str(res)
List of 3
 $ :'data.frame':       6 obs. of  2 variables:
  ..$ Age : chr [1:6] "1" "1" "2" "3" ...
  ..$ Year: chr [1:6] "10" "11" "10" "11" ...
 $ :'data.frame':       6 obs. of  2 variables:
  ..$ Age : chr [1:6] "1" "1" "2" "3" ...
  ..$ Year: chr [1:6] "12" "14" "10" "11" ...
 $ :'data.frame':       6 obs. of  2 variables:
  ..$ Age : chr [1:6] "1" "1" "2" "3" ...
  ..$ Year: chr [1:6] "12" "14" "10" "11" ...

CodePudding user response:

Using dplyr and purrr -

library(dplyr)
library(purrr)

mylist <- map(mylist, ~.x %>% mutate(across(.fns = as.character))) 
str(mylist)

#List of 3
# $ :'data.frame':  6 obs. of  2 variables:
#  ..$ Age : chr [1:6] "1" "1" "2" "3" ...
#  ..$ Year: chr [1:6] "10" "11" "10" "11" ...
# $ :'data.frame':  6 obs. of  2 variables:
#  ..$ Age : chr [1:6] "1" "1" "2" "3" ...
#  ..$ Year: chr [1:6] "12" "14" "10" "11" ...
# $ :'data.frame':  6 obs. of  2 variables:
#  ..$ Age : chr [1:6] "1" "1" "2" "3" ...
#  ..$ Year: chr [1:6] "12" "14" "10" "11" ...

Or a shorter version using only purrr (suggested by @Konrad Rudolph )

map(mylist, map_dfr, as.character)
  • Related