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.
You can convert the column “Fee” to a string by simply using DataFrame. apply(str) , for example df["Fee"]=df["Fee"].
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
To convert a list to a string in one line, use either of the three methods: Use the ''. join(list) method to glue together all list elements to a single string. Use the list comprehension method [str(x) for x in lst] to convert all list elements to type string.
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" ...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With