System (awk) command saved as a variables error

Viewed 51

I am having the following error:

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

However, I am getting the following error:

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

I am wondering if I have to escape the internal apostrophe's but not sure how?!

2 Answers

There are a couple errors in the code. The code below works for me and (per your comment) returns a two column data frame:

a <- system("awk '{ if (/foo/) print 2 \"\t\" $0; else print 1 \"\t\" $0; }' 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

Created on 2022-03-23 by the reprex package (v2.0.1)

I had an error with the seperator's and also wanted to keep the headers. I subsequently did the following, as I wanted to change the order.

file:
Header1 Header2
foo     bar
bar     bar
foo     foo

I then ran the command:

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

Now the output:

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

All works perfectly now. Thanks

Related