0

I am trying to pass variable as an argument to system command in R.

> system("ls>abc.csv")  #this works
> k<-"abc.csv"          
> system("ls>k")        #this does not work
> system2("ls>k")       #this does not work
sh: ls>k: command not found
> system("ls>$k")      #this does not work
sh: $k: ambiguous redirect
2
  • 1
    You need to actually construct the string as you want it to read. Look into sprintf, paste, or any other string manipulation/concatenation function. Commented Mar 19, 2019 at 19:29
  • You can paste in the variable value to the string system(paste0("ls>", k)) Commented Mar 19, 2019 at 19:29

3 Answers 3

1

You can use paste to build the OS command and pass to system

system(paste("ls >", k))
Sign up to request clarification or add additional context in comments.

Comments

0

The problem here is that R does not recognize variable k if you put it in a string. But indeed it is very useful to put the file name in a variable if you want to use it again and again.

Can you try

system(paste0("ls>", k))

If this works, you can also write a small function:

"%&%" <- function(a, b)paste0(a, b)

And then you can do

system("ls>"%&%k)

Comments

0

You can first define a string with the message you want, for instance mystr=paste("ls", "/data/files/"), then call system as system(mystr), and it will work. Actually it is almost the same answer as above with more emphasis on the creating message as a string first

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.