使用R语言format函数:仅为超宽最后一行添加空格的实现问询
R语言format函数仅为最后一行补空格的实现需求
我在用R的format函数处理数据时,遇到一个情况:只有最后一行的内容超出了设定的宽度范围,我希望仅为该行添加空格来对齐,其他行保持原有格式。我写了如下代码:
a <- c(1 : 8) b <- rep(43, 8) c <- c(16, 19, 20, 22, 28, 28, 28, 28) d <- c(-2814, -1474, -1012, -2, -1.6739, -0.012139, -0.31399, -2.5296E-06) e <- c("Others 2107", "Others 2110", "Others 2111", "Others 2113", "Others 2119", "Others 2119", "Others 2119", "Others 2119") a1 <- format(a, width = 10, justify = "right") b1 <- format(cbind(b, c), width = 9, justify = "right") c1 <- format(d, width = 10, justify = "right") d1 <- format(e, justify = "left") lines <- cbind(a1, b1, c1, d1) lines <- apply(lines, 1, paste0, collapse = " ") print(lines)
当前输出结果:
1 43 16 -2814 Others 2107 2 43 19 -1474 Others 2110 3 43 20 -1012 Others 2111 4 43 22 -2 Others 2113 5 43 28 -1.6739 Others 2119 6 43 28 -0.012139 Others 2119 7 43 28 -0.31399 Others 2119 8 43 28 -2.5296E-06 Others 2119
我期望得到的结果:
1 43 16 -2814 Others 2107 2 43 19 -1474 Others 2110 3 43 20 -1012 Others 2111 4 43 22 -2 Others 2113 5 43 28 -1.6739 Others 2119 6 43 28 -0.012139 Others 2119 7 43 28 -0.31399 Others 2119 8 43 28 -2.5296E-06 Others 2119
解决方案
核心思路是先计算出d列所有元素格式化后的最大宽度,让前面的行按该最大宽度减一的尺寸格式化,最后一行用最大宽度,实现仅为最后一行补空格对齐的效果。
修改后的代码如下:
a <- c(1 : 8) b <- rep(43, 8) c <- c(16, 19, 20, 22, 28, 28, 28, 28) d <- c(-2814, -1474, -1012, -2, -1.6739, -0.012139, -0.31399, -2.5296E-06) e <- c("Others 2107", "Others 2110", "Others 2111", "Others 2113", "Others 2119", "Others 2119", "Others 2119", "Others 2119") # 计算d列所有元素格式化后的最大宽度 formatted_d <- format(d, justify = "right") max_width <- max(nchar(formatted_d)) # 前7行用max_width-1的宽度,最后一行用max_width c1 <- ifelse(seq_along(d) < length(d), format(d, width = max_width - 1, justify = "right"), format(d, width = max_width, justify = "right")) a1 <- format(a, width = 10, justify = "right") b1 <- format(cbind(b, c), width = 9, justify = "right") d1 <- format(e, justify = "left") lines <- cbind(a1, b1, c1, d1) lines <- apply(lines, 1, paste0, collapse = " ") print(lines)
运行这段代码后,就能得到期望的输出效果。
内容的提问来源于stack exchange,提问作者YUHWAN SEO
相关产品推荐
相关产品推荐

