【问题标题】:How do we insert \n every n-character or/and after n-th space in a string in R?我们如何在 R 中的字符串中的每个 n 个字符或/和第 n 个空格之后插入 \?
【发布时间】:2022-02-11 07:31:24
【问题描述】:

在 SO 我找到了一个解决方案,它有助于在字符串中的每个第 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"
) 

我想让它按行列表/拆分,所以我想插入\n

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

【问题讨论】:

  • 类似cat(gsub("(\\S+(?:\\s+\\S+){2})\\s*", "\\1\n", x)) 的东西分成三个字(n-1={2})?

标签: r word-wrap


【解决方案1】:

您正在重新发明轮子。 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" 

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

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

编辑

使用新添加的例子:

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~

【讨论】:

    猜你喜欢
    • 2020-05-21
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多