Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
假设我有一个指定长度的数字向量。
x = c(3,5,4,10)
然后我运行 cumsum 来获取他们的范围。
cumsum(x) 3 8 12 22
我如何将每个配对以产生成对的范围,从 1 开始。
最好作为字符向量:
c("1-3", "3-8", "8-12", "12-22")
你可以这样使用paste:
paste
paste(c(1, cumsum(x))[-(length(x)+1)], cumsum(x), sep = "-") # [1] "1-3" "3-8" "8-12" "12-22"
另一种选择是使用sprintf
sprintf
x1 <- c(1, cumsum(x)) sprintf('%d-%d', x1[-length(x1)], x1[-1]) #[1] "1-3" "3-8" "8-12" "12-22"