系统(awk)命令保存为变量错误

System (awk) command saved as a variables error

我遇到以下错误:

a <- system("awk '{ if (/foo/) print "2","\t",[=10=]; else print "1","\t",[=10=]; }' file",intern=true)

但是,我收到以下错误:

Error: unexpected numeric constant in "a \<- system("awk '{ if (/foo/) print "2"

我想知道是否必须转义内部撇号但不确定如何转义?!

代码中有几个错误。下面的代码适用于我和(根据您的评论)returns 两列数据框:

a <- system("awk '{ if (/foo/) print 2 \"\t\" [=10=]; else print 1 \"\t\" [=10=]; }' file", intern = TRUE)
DF = read.table(text = a, sep = "\t")
DF
#>   V1  V2
#> 1  2 foo
#> 2  1 bar
#> 3  1 asd

summary(DF)
#>        V1             V2           
#>  Min.   :1.000   Length:3          
#>  1st Qu.:1.000   Class :character  
#>  Median :1.000   Mode  :character  
#>  Mean   :1.333                     
#>  3rd Qu.:1.500                     
#>  Max.   :2.000

reprex package (v2.0.1)

于 2022-03-23 创建

我的分隔符有误,还想保留 headers。我随后做了以下操作,因为我想更改顺序。

file:
Header1 Header2
foo     bar
bar     bar
foo     foo

然后我运行命令:

a <- system("awk '{ if (/foo/) print 2 \"\t\" [=11=]; else print 1 \"\t\" [=11=]; }' file | awk '{print ,,}' ", intern = TRUE)
DF = read.table(text = a, sep = " ", header=TRUE)
colnames(DF)[3] <- "Header3"

现在输出:

DF
Header1 Header2 Header3
foo     bar     2
bar     bar     1
foo     foo     2

现在一切正常。谢谢