Using toString function in R

旧巷老猫 提交于 2021-01-03 18:55:02

问题


I have numeric objects a=1,b=2,c=3,d=4. Now when I use :

toString(c(a,b,c,d))

I get:

"1, 2, 3, 4"

as the output. How do I get rid of the comma? I want "1234" as the output. Or is there another way to do this?


回答1:


Just use paste or paste0:

a <- 1; b <- 2; c <- 3; d <- 4
paste0(a, b, c, d)
# [1] "1234"
paste(a, b, c, d, sep="")
# [1] "1234"

You cannot get the result directly from toString even though toString uses paste under the hood:

toString.default
# function (x, width = NULL, ...) 
# {
#     string <- paste(x, collapse = ", ")
# --- function continues ---

Compare that behavior with:

paste(c(a, b, c, d), collapse = ", ")
# [1] "1, 2, 3, 4"

Since it is hard-coded, if you really wanted to use toString, you would have to then use sub/gsub to remove the "," after you used toString, but that seems inefficient to me.



来源:https://stackoverflow.com/questions/21213856/using-tostring-function-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!