简体   繁体   English

在 R 中格式化打印 output

[英]Formatting a printing output in R

I have a data as我有一个数据

-418 -26066 -539 -33810
-763 -47745 207 12395
-701 14732 473 -8748
 862 -19061 744 -16347
680 59377 -637 -53885
-720 35840 -486 23906
-147 3505 762 -20129
677 -53800 849 -67388
-690 42730 995 -63425
203 -4108 620 -11614
93 -6381 26 -1423
-230 -6255 135 3600
498 -8020 341 -5665
855 -35988 306 -12381
69 -4017 -329 17475

and my code is我的代码是

library(data.table)

x1 <- Problem10_data$V1
y1 <- Problem10_data$V2
x2 <- Problem10_data$V3
y2 <- Problem10_data$V4

a = (y2 - y1) / (x2 - x1)
b = (x2*y1 - x1*y2) / (x2 - x1)

points <- transpose(data.frame(a = a, b = b))

for (var in points){
  cat('(', var, ')', sep = " ")
}

my output is我的 output 是

( 64 686 )( 62 -439 )( -20 712 )

but what I want is但我想要的是

(64 686) (62 -439) (-20 712) 

so I have tried using also print and doing formatting etc. But I could not succeed.所以我也尝试过使用打印和格式化等。但我无法成功。 Any help would be appreciated.任何帮助,将不胜感激。

How about this using sprintf()使用sprintf()怎么样

Problem10_data <- tibble::tribble(
~V1, ~V2, ~V3, ~V4, 
-418, -26066, -539, -33810,
-763, -47745, 207, 12395,
-701, 14732, 473, -8748,
862, -19061, 744, -16347,
680, 59377, -637, -53885,
-720, 35840, -486, 23906,
-147, 3505, 762, -20129,
677, -53800, 849, -67388,
-690, 42730, 995, -63425,
203, -4108, 620, -11614,
93, -6381, 26, -1423,
-230, -6255, 135, 3600,
498, -8020, 341, -5665,
855, -35988, 306, -12381,
69, -4017, -329, 17475)

sprintf("(%.0f %.0f)", points[1,], points[2,])
# [1] "(64 686)"   "(62 -439)"  "(-20 712)"  "(-23 765)"  "(86 897)"   "(-51 -880)" "(-26 -317)" "(-79 -317)"
# [9] "(-63 -740)" "(-18 -454)" "(-74 501)"  "(27 -45)"   "(-15 -550)" "(-43 777)"  "(-54 -291)"

Or, if it needs to be all in one string:或者,如果它需要全部在一个字符串中:

paste(sprintf("(%.0f %.0f)", points[1,], points[2,]), collapse=" ")
# [1] "(64 686) (62 -439) (-20 712) (-23 765) (86 897) (-51 -880) (-26 -317) (-79 -317) (-63 -740) (-18 -454) (-74 501) (27 -45) (-15 -550) (-43 777) (-54 -291)"

Why not using this small modification to your cat statement?为什么不对你的cat语句使用这个小修改呢?

cat("(",paste(var,collapse=" "),") ",sep="")

I am considering this simplified example:我正在考虑这个简化的例子:

points=list(c(1,-2),c(10,-20)) 
for (var in points)
cat("(",paste(var,collapse=" "),") ",sep="")

I get我明白了

(1 -2) (10 -20)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM