简体   繁体   English

R | 将Cat()输出分配给变量

[英]R | Assign Cat() output to variable

I am trying to remove the '\\' that is generated, so i run cat() to clear it. 我试图删除生成的“ \\”,所以我运行cat()清除它。 But need to assign that output to a variable to later match in a gsubfn string. 但是需要将该输出分配给变量,以便以后在gsubfn字符串中进行匹配。

>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

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. 正如注释中已经指出的那样,将cat的输出分配给变量将无济于事,因为\\字符(称为转义字符 )实际上并不存在于字符串中。 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输出的人员的利益,必须提供更完整的答案。 cat does have some useful features for formatting output, which someone may have a valid need to store in a variable. cat确实具有一些用于格式化输出的有用功能,某些人可能确实需要将其存储在变量中。 In these instances, we can use capture.output to achieve this. 在这些情况下,我们可以使用capture.output实现此目的。 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: 它创建一个字符向量x,每个元素对应于输出的一行:

# [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')

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

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