R中的cat函数
cat function in R
我有这样一个数据框:
>result
x y
1 82 10
2 82 90
3 82 10
4 82 50
5 82 10
6 82 50
7 82 10
8 6 7
9 6 7
10 6 7
11 6 7
12 3 7
13 3 7
14 2 7
我想使用 cat
函数以标准格式打印数据框。我在这里使用了一个简单的条件。如果 x < y,它将打印 (x, y) else ( )。但我没有得到所需的输出格式。这是我的代码:
apply(result, 1, function(x) {
if( x[1] < x[2]) cat(paste0( "(", x ,")\n" )) else cat(paste( "(", " " ,")\n" ))
})
>
( )
(82)
(90)
( )
( )
( )
( )
( )
(6)
(7)
(6)
(7)
(6)
(7)
(6)
(7)
(3)
(7)
(3)
(7)
(2)
(7)
我得到的是 (x) (y) 而不是 (x, y)。输出应该是这样的
( )
(82, 90)
( )
( )
( )
( )
( )
(6, 7)
(6, 7)
(6, 7)
(6, 7)
(3, 7)
(3, 7)
(2, 7)
-- 数据
structure(list(x = c(82L, 82L, 82L, 82L, 82L, 82L, 82L, 6L, 6L,
6L, 6L, 3L, 3L, 2L), y = c(10L, 90L, 10L, 50L, 10L, 50L, 10L,
7L, 7L, 7L, 7L, 7L, 7L, 7L)), class = "data.frame", row.names = c(NA,
-14L))
我们可能需要折叠或使用toString
invisible(apply(result, 1, function(x) {
if( x[1] < x[2]) cat(paste0( "(",toString( x) ,")\n" )) else cat(paste( "(", " " ,")\n" ))
}))
-输出
( )
(82, 90)
( )
( )
( )
( )
( )
(6, 7)
(6, 7)
(6, 7)
(6, 7)
(3, 7)
(3, 7)
(2, 7)
如果您想保留 data.frame,您可以执行以下操作:
library(dplyr)
df %>%
mutate(print = if_else(x < y, paste0( "(", x,",",y,")" ),"( )"))
x y print
1 82 10 ( )
2 82 90 (82,90)
3 82 10 ( )
4 82 50 ( )
5 82 10 ( )
6 82 50 ( )
7 82 10 ( )
8 6 7 (6,7)
9 6 7 (6,7)
10 6 7 (6,7)
11 6 7 (6,7)
12 3 7 (3,7)
13 3 7 (3,7)
14 2 7 (2,7)
我有这样一个数据框:
>result
x y
1 82 10
2 82 90
3 82 10
4 82 50
5 82 10
6 82 50
7 82 10
8 6 7
9 6 7
10 6 7
11 6 7
12 3 7
13 3 7
14 2 7
我想使用 cat
函数以标准格式打印数据框。我在这里使用了一个简单的条件。如果 x < y,它将打印 (x, y) else ( )。但我没有得到所需的输出格式。这是我的代码:
apply(result, 1, function(x) {
if( x[1] < x[2]) cat(paste0( "(", x ,")\n" )) else cat(paste( "(", " " ,")\n" ))
})
>
( )
(82)
(90)
( )
( )
( )
( )
( )
(6)
(7)
(6)
(7)
(6)
(7)
(6)
(7)
(3)
(7)
(3)
(7)
(2)
(7)
我得到的是 (x) (y) 而不是 (x, y)。输出应该是这样的
( )
(82, 90)
( )
( )
( )
( )
( )
(6, 7)
(6, 7)
(6, 7)
(6, 7)
(3, 7)
(3, 7)
(2, 7)
-- 数据
structure(list(x = c(82L, 82L, 82L, 82L, 82L, 82L, 82L, 6L, 6L,
6L, 6L, 3L, 3L, 2L), y = c(10L, 90L, 10L, 50L, 10L, 50L, 10L,
7L, 7L, 7L, 7L, 7L, 7L, 7L)), class = "data.frame", row.names = c(NA,
-14L))
我们可能需要折叠或使用toString
invisible(apply(result, 1, function(x) {
if( x[1] < x[2]) cat(paste0( "(",toString( x) ,")\n" )) else cat(paste( "(", " " ,")\n" ))
}))
-输出
( )
(82, 90)
( )
( )
( )
( )
( )
(6, 7)
(6, 7)
(6, 7)
(6, 7)
(3, 7)
(3, 7)
(2, 7)
如果您想保留 data.frame,您可以执行以下操作:
library(dplyr)
df %>%
mutate(print = if_else(x < y, paste0( "(", x,",",y,")" ),"( )"))
x y print
1 82 10 ( )
2 82 90 (82,90)
3 82 10 ( )
4 82 50 ( )
5 82 10 ( )
6 82 50 ( )
7 82 10 ( )
8 6 7 (6,7)
9 6 7 (6,7)
10 6 7 (6,7)
11 6 7 (6,7)
12 3 7 (3,7)
13 3 7 (3,7)
14 2 7 (2,7)