Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R | Assign Cat() output to variable

Tags:

string

r

cat

I am trying to remove the '\' that is generated, so i run cat() to clear it. But need to assign that output to a variable to later match in a gsubfn string.

>topheader <-'<div id="editor1" class="shinytinymce shiny-bound-input" 
style="resize: none; width: 100%; height: 100%; border-style: none; 
background: gainsboro;">'

>topheader
[1] "<div id=\"editor1\" class=\"shinytinymce shiny-bound-input\" 
style=\"resize: none; width: 100%; height: 100%; border-style: none; 
background: gainsboro;\">"

>cat(topheader)
[1] <div id="editor1" class="shinytinymce shiny-bound-input" style="resize: 
none; width: 100%; height: 100%; border-style: none; background: 
gainsboro;">

> test<-cat(topheader)


> test
NULL
like image 969
Koolakuf_DR Avatar asked Oct 28 '22 22:10

Koolakuf_DR


1 Answers

As indicated already in the comments, assigning the output of cat to a variable won't help you, because the \ characters (referred to as an escape characters) don't actually exist in the character string. They are just printed that way when you output the character string to the console.

However, for the benefit of other people who are trying to assign the output of cat for a different reason, a more complete answer is warranted. cat does have some useful features for formatting output, which someone may have a valid need to store in a variable. In these instances, we can use capture.output to achieve this. For example,

cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))

produces the following output, conveniently split into numbered lines at the width of the console:

# {1}: a 100 b 200 c 300 d 400 e 500 f 600 g 700 h 800 i 900 
# {2}: j 1000 k 1100 l 1200 m 1300 n 1400 o 1500 p 1600 
# {3}: q 1700 r 1800 s 1900 t 2000 u 2100 v 2200 w 2300 
# {4}: x 2400 y 2500 z 2600

we can capture this output by

x = capture.output(
      cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))
    )

which creates a character vector, x, with each element corresponding to a line of the output:

# [1] "{1}: a 100 b 200 c 300 d 400 e 500 f 600 g 700 h 800 i 900 "
# [2] "{2}: j 1000 k 1100 l 1200 m 1300 n 1400 o 1500 p 1600 "     
# [3] "{3}: q 1700 r 1800 s 1900 t 2000 u 2100 v 2200 w 2300 "     
# [4] "{4}: x 2400 y 2500 z 2600"  

If you like, you can collapse this vector into a single string separated with line breaks using:

x = paste0(x, collapse = '\n')
like image 162
dww Avatar answered Nov 15 '22 07:11

dww