Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R |将Cat()输出分配给变量_R_String_Cat - Fatal编程技术网

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

R |将Cat()输出分配给变量,r,string,cat,R,String,Cat,我试图删除生成的“\”,因此运行cat()将其清除。但需要将该输出分配给变量,以便稍后在gsubfn字符串中匹配 >topheader <-'<div id="editor1" class="shinytinymce shiny-bound-input" style="resize: none; width: 100%; height: 100%; border-style: none; background: gainsboro;">' >topheader

我试图删除生成的“\”,因此运行cat()将其清除。但需要将该输出分配给变量,以便稍后在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
>topheader topheader
[1] ""
>cat(上收割台)
[1] 
>测试
无效的

如注释中所示,将
cat
的输出分配给变量对您没有帮助,因为
\
字符(称为an)实际上不存在于字符串中。当您将字符串输出到控制台时,它们就是这样打印的

然而,为了其他出于不同原因试图分配cat输出的人的利益,需要一个更完整的答案
cat
确实有一些用于格式化输出的有用功能,有些人可能需要将这些功能存储在变量中。在这些情况下,我们可以使用
capture.output
来实现这一点。比如说,

cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))
生成以下输出,在控制台的宽度处方便地拆分为带编号的行:

# {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
我们可以通过

x = capture.output(
      cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))
    )
它创建一个字符向量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"  
如果愿意,可以使用以下方法将此向量折叠为单个字符串,并用换行符分隔:

x = paste0(x, collapse = '\n')

你不能
cat
始终返回
NULL
。它严格用于打印到控制台/文件。这些反斜杠只是为了逃避内部引用。它们实际上不在那里。@richscriben实际上您可以使用
capture.output()
cat
分配输出。然而,这在这里没有帮助,因为真正的问题是其他的。。。。(见下一条评论)。@DannyRamirez你有一个基本的误解。\characters实际上不存在于字符串中-当您将输出打印到控制台时,
print
会以这种方式显示它们。请尝试
nchar(“\'editor1\”)
。它输出9而不是11。如果使用
capture.output
则会遇到同样的问题。