我们如何在 R 中的字符串中的每个 n 个字符或/和后面插入 \n ?

rg4*_*g4s 1 r word-wrap

因此,我找到了一个解决方案,有助于在字符串中的每个第 n 个字符插入一个值/字符:

(?=(?:.{n})+$)

\n但每隔 n 个空格插入一个值(例如制表符或 )会更合理,这样单词就不会被拆分。编辑此正则表达式有哪些可能的方法?

我进行了聚类分析,现在我想将标签附加到树状图上。考虑到标签是非常长的字符串,例如:

tibble(
   id = d2022_1,
   label = "A very long label for the dendro that should be splitted so it will look nicely in the picture"
) 
Run Code Online (Sandbox Code Playgroud)

我想将其按行制成表格/分割,所以我想插入\n

A very long label for the dendro\nthat should be splitted so\nit will look nicely in the picture

All*_*ron 12

你在这里重新发明轮子。R 包含strwrap可以在适当的单词边界分割长字符串的函数。与在 n 个空格后创建中断相比,这可以提供更一致的行长度。

例如,假设我最多希望每 12 个字符换行一次。我可以:

string <- "The big fat cat sat flat upon the mat"

strwrap(string, width = 12)
#> [1] "The big fat" "cat sat"     "flat upon"   "the mat" 
Run Code Online (Sandbox Code Playgroud)

如果您想要换行而不是分割字符串,只需使用折叠粘贴结果即可:

paste(strwrap(string, width = 12), collapse = "\n")
[1] "The big fat\ncat sat\nflat upon\nthe mat"
Run Code Online (Sandbox Code Playgroud)

编辑

使用新添加的示例:

df <- tibble(
  id = "d2022_1",
  label = rep("A very long label for the dendro that should be splitted so it will look nicely in the picture", 2)
)

df
#> # A tibble: 2 x 2
#>   id      label                                                                        
#>   <chr>   <chr>                                                                        
#> 1 d2022_1 A very long label for the dendro that should be splitted so it will look nic~
#> 2 d2022_1 A very long label for the dendro that should be splitted so it will look nic~

df %>% mutate(label = sapply(label, function(x) paste(strwrap(x, 20), collapse = "\n")))
#> # A tibble: 2 x 2
#>   id      label                                                                        
#>   <chr>   <chr>                                                                        
#> 1 d2022_1 "A very long label\nfor the dendro that\nshould be splitted\nso it will look~
#> 2 d2022_1 "A very long label\nfor the dendro that\nshould be splitted\nso it will look~
Run Code Online (Sandbox Code Playgroud)