向量,a并且b可以toString(width = 10)在 Base R 中使用縮短,從而產生以....
但是,我想知道如何使縮短的向量以 結尾..., last vector element?
我desired_output的如下所示。
a <- 1:26
b <- LETTERS
toString(a, width = 10)
# [1] "1,2,...."
desired_output1 = "1,2,...,26"
toString(b, width = 10)
# [1] "A,B,...."
desired_output2 = "A,B,...,Z"
uj5u.com熱心網友回復:
你可以只添加結尾。
paste(toString(a, width = 10), a[length(a)], sep=", ")
[1] "1, 2, ...., 26"
paste(toString(b, width = 10), b[length(b)], sep=", ")
[1] "A, B, ...., Z"
uj5u.com熱心網友回復:
應用后toString,我們可以使用sub洗掉子字串format
f1 <- function(vec, n = 2) {
gsub("\\s ", "",
sub(sprintf("^(([^,] , ){%s}).*, ([^,] )$", n), "\\1...,\\3", toString(vec)))
}
-測驗
> f1(a)
[1] "1,2,...,26"
> f1(b)
[1] "A,B,...,Z"
> f1(a, 3)
[1] "1,2,3,...,26"
> f1(b, 3)
[1] "A,B,C,...,Z"
> f1(a, 4)
[1] "1,2,3,4,...,26"
> f1(b, 4)
[1] "A,B,C,D,...,Z"
uj5u.com熱心網友回復:
我們可以這樣做:創建一個函式,提取向量的前兩個元素和最后一個元素并將它們粘貼在一起:
my_func <- function(x) {
a <- paste(x[1:2], collapse=",")
b <- tail(x, n=1)
paste0(a,",...,",b)
}
my_func(a)
[1] "1,2,...,26"
my_func(b)
[1] "A,B,...,Z"
uj5u.com熱心網友回復:
library(stringr)
a <- 1:26
b <- LETTERS
reduce_string <- function(x, n_show) {
str_c(x[1:n_show], collapse = ',') %>%
str_c('....,', x[[length(x)]])
}
reduce_string(a, 2)
#> [1] "1,2....,26"
由reprex 包(v2.0.1)于 2022 年 1 月 2 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403644.html
標籤:
上一篇:將所有其他元音設為向量大寫
