Home > Back-end >  cat function in R
cat function in R

Time:09-27

I have a data frame like this:

>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

I want to print the data frame in standard format using cat function. I used a simple condition here. If x < y, it will print (x, y) else ( ). But I am not getting the desired output format. Here is my code:

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)

I am getting (x) (y) instead of (x, y). The output should be like this

(   )
(82, 90)
(   )
(   )
(   )
(   )
(   )
(6, 7)
(6, 7)
(6, 7)
(6, 7)
(3, 7)
(3, 7)
(2, 7)

-- data

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))

CodePudding user response:

We may need to collapse or use toString

apply(result, 1, function(x) {
  if( x[1] < x[2]) cat(paste0( "(",toString( x) ,")\n" )) else cat(paste( "(", " " ,")\n" ))
})

-output

(   )
(82, 90)
(   )
(   )
(   )
(   )
(   )
(6, 7)
(6, 7)
(6, 7)
(6, 7)
(3, 7)
(3, 7)
(2, 7)

CodePudding user response:

In case you want to keep your data.frame you could the following:

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)
  • Related