Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
508 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...