tidyverse 包中的 R 函数是什么,它允许您向 start/end 字符串添加一些字符?

What is the R function in the tidyverse package which allows you add some characters to the start/end a string?

(请注意,我是 coding/r 编程的新手,所以我觉得这有点困难。)

例如,我有一个简单的学生数据集和他们各自的权重。

Class <- c("Tom", "Ana", "John", "Sara")
Weight <- c(50, 45, 52, 47)
df <- data.frame(Class, Weight)

如何将“公斤”单位添加到“重量”变量中每个重量的末尾,而无需手动输入?

(我认为这可以使用 stringr 包来完成,但我不确定。)

非常感谢, 卡里玛

您可以使用 base R 中的 paste0(如果您不想要依赖性则很好),或者 stringr::str_c(如果您使用很多其他 stringr职能)。虽然一些 stringr 函数比它们的基本对应函数具有优势,但这对函数在本质上是相同的。

df %>% mutate(Weight = str_c(Weight, "kg"))

作为参考,您可以看到这相当于 paste0:

assertthat::are_equal(
  df %>% mutate(Weight = str_c(Weight, "kg")),
  df %>% mutate(Weight = paste0(Weight, "kg"))
) # TRUE