在R中使用paste0,带有文本和 Dataframe 列,但文本不重复

flseospp  于 2023-03-05  发布在  其他
关注(0)|答案(2)|浏览(155)

下面是一些示例代码:

df1<-data.frame(Name=c("John","Steve","Andy"),
                Age=c(24,19,36))
paste0("Hi here is the list of names: ",df1$Name,". I hope that works")

输出变为:
[1]"嗨,这里是名单:约翰,我希望这能奏效。"
[2]"嗨,这里是名单:史蒂夫。我希望这能奏效。"
[3]"嗨,这里是名单:安迪。我希望这能奏效。"

  • 但我想要的是 *

嗨这里是名单:约翰,史蒂夫,安迪。我希望这能奏效。"
有没有一种方法可以像这样粘贴特定的列引用,而不会出现重复的问题?

gijlo24d

gijlo24d1#

在粘贴之前,需要将df$Name折叠成一个字符串。可以使用另一个paste()调用(带有collapse参数),或者使用方便的toString函数,该函数会自动将长度为n的字符串转换为长度为1且包含逗号和空格的字符串,就像这里所需要的那样。

paste0(
  "Hi here is the list of names: ", 
  toString(df1$Name),
  ". I hope that works"
)
# [1] "Hi here is the list of names: John, Steve, Andy. I hope that works"

## or 

paste0(
  "Hi here is the list of names: ",
  paste(df1$Name, collapse = ", ") ,
  ". I hope that works"
)
# [1] "Hi here is the list of names: John, Steve, Andy. I hope that works"

有时候我更喜欢sprintf而不是paste来进行填空风格的字符串操作,它可能更具可读性:

sprintf(
  "Hi here is the list of names: %s. I hope that works", 
  toString(df1$Name)
)
# [1] "Hi here is the list of names: John, Steve, Andy. I hope that works"
vyswwuz2

vyswwuz22#

我们可以使用gluetoString在单个调用中完成此操作:glue是我用来动态生成需要填充数据的字符串的工具。

library(glue)

glue("Hi here is the list of names: {toString(df1$Name)}. I hope that works")

Hi here is the list of names: John, Steve, Andy. I hope that works

相关问题