6

For example, this PowerShell command returns the top 5 largest files in the directory:

gci -r |sort Length -desc |select fullname -f 5

Is it possible to run it in R and assign it to a variable?

I tried this:

system("gci -r|sort Length -desc|select fullname -f 5")
Warning message:
running command 'gci -r|sort Length -desc|select fullname -f 5' had status 127 

Shouldn't I use system() here?

Waldi
  • 39,242
  • 6
  • 30
  • 78
Nick
  • 8,451
  • 13
  • 57
  • 106

1 Answers1

10

You'll probably need to run it as (assuming PowerShell is in your path):

system("powershell -command \"gci -r|sort Length -desc|select fullname -f 5\"")

or, if you're not keen on escaping " with \".

system('powershell -command "gci -r|sort Length -desc|select fullname -f 5"')

I'm also assuming that's how R escapes and embeds quotes in strings (from my cursory googling about string handling in R).

If you wish to capture the output to a variable (specifically, a character vector) you need to use the intern = TRUE argument:

res <- system('powershell -command "gci -r|sort Length -desc|select fullname -f 5"', intern=TRUE)

For more information see:

http://stat.ethz.ch/R-manual/R-patched/library/base/html/system.html

In particular:

If intern = TRUE, a character vector giving the output of the command, one line per character string.

and

If intern = FALSE, the return value is an error code (0 for success),

Kev
  • 118,037
  • 53
  • 300
  • 385
  • That works! When I try to assign it to a `var`, I got `var [1] 0` `typeof(var) [1] "integer"` How to assign the output content to a var? – Nick Jun 10 '15 at 00:50
  • @Nick - have updated my answer, but I'm at the limit of my R knowledge, I only installed it to verify my suspicions about why PowerShell wasn't launching. :) – Kev Jun 10 '15 at 01:22
  • Thank you very much for the explaination. – Nick Jun 10 '15 at 04:05