Reputation: 35
Surprisingly, I haven't found any satisfying answer through my own research.
Suppose I have following list:
bc <- list(row0 = 1, row1 = c(1, 1), row2 = c(1L, 2, 1), row3 = c(1, 3, 3, 1))
And I want to convert all numbers in that list into integers. My first unsophisticated approach would be to just place an "L" after each numbers. This approach would work but it is quite unhandy.
Second, I've tried
as.integer(bc[[1]])
But this does not save the variable in the list as integers.
Third, I've tried something similar suggested in another thread:
as.integer(unlist(bc))
Which indeed "unlists the list" and converts the number into integers, however, I'm now stuck when I want to restore the exact same list as before again with list names.
There has to be a faster approach then this?
Thank you very much!
Upvotes: 1
Views: 417
Reputation: 21992
The map()
function from purrr
should help:
map(bc, as.integer)
# $row0
# [1] 1
#
# $row1
# [1] 1 1
#
# $row2
# [1] 1 2 1
#
# $row3
# [1] 1 3 3 1
str(purrr::map(bc, as.integer))
# List of 4
# $ row0: int 1
# $ row1: int [1:2] 1 1
# $ row2: int [1:3] 1 2 1
# $ row3: int [1:4] 1 3 3 1
The same result could be obtained with lapply(bc, as.integer)
if you're in more of a base R kind of mood.
Upvotes: 3