缩短 R 中的长向量
Shortening a long vector in R
向量 a
和 b
可以使用 Base R 中的 toString(width = 10)
缩短,导致更短的向量以 ....
结尾
但是,我想知道如何使缩短的向量以 ..., 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"
应用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"
你可以加上结尾。
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"
我们可以这样做:
创建一个函数来提取向量的前两个元素和最后一个元素并将它们粘贴在一起:
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"
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 package (v2.0.1)
创建于 2022-01-02
向量 a
和 b
可以使用 Base R 中的 toString(width = 10)
缩短,导致更短的向量以 ....
但是,我想知道如何使缩短的向量以 ..., 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"
应用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"
你可以加上结尾。
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"
我们可以这样做: 创建一个函数来提取向量的前两个元素和最后一个元素并将它们粘贴在一起:
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"
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 package (v2.0.1)
创建于 2022-01-02