Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unlist without creating decimals

Tags:

r

I did not find a dupe, although this certainly must have been asked before :/

How do I unlist a list (or even a vector) of numerics without creating decimals in those elements that do not have decimals in the first place (pun semi-intended).

unlist(list(1, 1.11))
#> [1] 1.00 1.11
like image 529
tjebo Avatar asked Jan 01 '23 02:01

tjebo


1 Answers

formatC/prettyNum would also work for this:

formatC(unlist(list(1, 1.11)))
## [1] "1"    "1.11"

prettyNum(unlist(list(1, 1.11)))
## [1] "1"    "1.11"

Actually, as.character seems to be sufficient:

as.character(list(1, 1.11))
## [1] "1"    "1.11"

Though that works as you expect it only if the list elements are single values:

as.character(list(1, 1.11, c(2, 2.22), list(3, 3.33)))
## [1] "1"             "1.11"          "c(2, 2.22)"    "list(3, 3.33)"

From the help file for as.character:

For lists and pairlists (including language objects such as calls) it deparses the elements individually, except that it extracts the first element of length-one character vectors.

In those cases, using as.character after unlist would make more sense:

as.character(unlist(list(1, 1.11, c(2, 2.22), list(3, 3.33))))
## [1] "1"    "1.11" "2"    "2.22" "3"    "3.33"
like image 192
A5C1D2H2I1M1N2O1R2T1 Avatar answered Jan 04 '23 20:01

A5C1D2H2I1M1N2O1R2T1