All the Windows CMD system commands

When developing in R, working with and wrangling data, or preparing for machine learning projects, there may be times when one has to use operating system instructions from/in R.

Let’s look at some of the most helpful cmd commands while using R in this blog article. Please keep in mind that the cmd commands are only applicable to the Windows environment; for Linux/MacOS, the system commands need be slightly modified, but the wrapper R code should stay unchanged.

 

  1. R commands to get access to the CMD

 

The following R commands are used for accessing, executing, and making modifications using cmd:

 

  • system
  • system2
  • shell
  • shell.exec

 

 

All of them execute the supplied and following OS command. All of the functions listed are included in the R basic package, as a result, no extra packages are required.

Assume we wish to begin with the DIR command and return the results in RStudio.

## 1 Simple dir command with order switch

system(“dir /o”)

system2(“dir /o”)

shell(“dir /o”)

shell.exec(“dir /o”)

 

and you will see that the shell command will return the results to the console pane in R Studio, whilst the others will not provide you with the appropriate data immediately. The major distinction is that a shell function will execute the required command within the shell (as defined by the POSIX standard, or you may discover POSIX functions here), but a system command would launch an OS command.

A collection of specialized functions is also available in the R Base package to establish, open, add, and close file and URL connections, as well as open and load compressed files. Simply listing the functions:

 

  • object connections: file, url
  • compression and encoding: gzfile, bzfile, xzfile, unz, pipe
  • connection functions: open,close,flush
  • boolean functions: isOpen, isIncomplete

 

When using default settings, the shell function will always work, however the system function will only operate when the system settings (paths) are properly setup. Example:

### Checking the usage

Sys.which(“copy”)

Sys.which(“ping”)

 

As a consequence, system and system2 functions will work for the ping CMD command, but not for the copy CMD command, or, as mentioned later in the weblog, the rename and move commands.

>

> ### Checking the usage

> Sys.which(“copy”)

Copy

“”

>Sys.which(“ping”)

ping

“C:\\WINDOWS\\SYSTEM32\\ping.exe”

>|

 

  1. Using R to chain CMD commands

For the sake of simplicity, let’s stick with the shell function and see how chaining may be accomplished.

 

The following example will not work since the environment is started every time the shell function is run. So running shell after shell will not work!

 

setwd(“C:\\Users\\SOSSupport”)

 

shell(“dir”)

shell(“cd ..”)

shell(“dir”)

 

 

Combining the cmd commands into a single command will work:

 

shell(“dir && cd .. && dir”)

 

Because this does not change your working directory, you will be returned to the initiated environment each time the shell is done. By verifying:

 

getwd()

 

The working directory has not changed, as you can see. When checking before and after the R environment variables, they will also be preserved:

 

Sys.getenv(c(“R_HOME”,”HOME”))

 

You may also specify the variable, utilize the echo command, or use built-in system variables such as %TIME%, among other things. Github has more information.

 

  1. The most common CMD commands run from R

The following are some CMD commands that we will encapsulate in R:

 

  • fc / compare
  • rename
  • move / copy
  • ping (pingpath)
  • systeminfo
  • tasklist (taskkill)
  • ipconfig / netstat

 

3.1. Using CMD to compare two files

The ability to compare two files in CMD is simply one of several techniques to determine if your dataset is identical.

 

Let’s make two *.csv files with the iris dataset and compare them in cmd:

setwd(“C:\\Users\\SOSSupport”)

 

#create two files

write.csv(iris, file=”iris_file1.csv”)

write.csv(iris, file=”iris_file2.csv”)

 

#compare both files

shell(“FC /a C:\\Users\\SOSSupport\\iris_file1.csv

C:\\Users\\SOSSupport\\iris_file2.csv”)

 

The following is the outcome data: FC: no differences were seen. The same as if the command were run from the command line:

 

Windows plus R

The same result may be obtained using the R function all.equal, which is included in the standard build.

 

file1 <- “C:\\Users\\SOSSupport\\iris_file1.csv”

file2 <- “C:\\Users\\SOSSupport\\iris_file2.csv”

 

# or in R using all.equal

all.equal(readLines(file1), readLines(file2))

 

Because we’re in R, we’d want the results to be saved in a data.frame. Let’s utilize the previously described System2 function to do this. This is an updated version of the System function that utilizes different arguments and commands as well as some extra options.

 

# run the same command using newer function “system2” and set the arguments

 

cmd_command <- “FC”

#cmd_args <- “/a C:\\Users\\SOSSupport\\iris_file1.csv

C:\\Users\\SOSSupport\\iris_file2.csv”

cmd_args <- c(‘/a’, file1, file2)

 

rr <- system2(command=cmd_command,

args= cmd_args,

stdout=TRUE,

stderr=TRUE,

wait = TRUE)

 

#suppose we want to store the results in data.frame

#empty dataframe

df_rr <- data.frame(file1 = character(),

file2 = character(),

fcompare = character(),

stringsAsFactors=FALSE)

 

#temporary results

temp <- data.frame(file1=file1, file2=file2, fcompare=rr[2])

 

#bind all into dataframe

df_rr <- rbind(df_rr, setNames(temp, names(df_rr)))

 

with the findings saved in data When comparing several files, use a frame.

 

3.2. Using CMD to rename a file

Keeping the iris dataset file: Let’s rename the file C:UsersSOSSupportiris file1.csv.

 

# renaming the file using shell command

shell(“cd c:\\users\\sossupport && ren iris_file1.csv iris_file1_copy.csv”)

 

and with the parameterized shell function (note that the copy will not work since Sys.which(“copy”) returns an empty string):

 

file_old_name <- “c:\\users\\SOSSupport\\iris_file2.csv”

file_new_name <- “iris_file2_new.csv”

 

cmd_command <- paste(“RENAME”, file_old_name, file_new_name)

 

# System2 Does not work

# system2(command=cmd_command)

shell(cmd_command)

 

The files are renamed in both cases. Fortunately or unfortunately, when there is no syntax mistake and the file exists, the result is none.

 

3.3. In CMD, copy a file

 

Keeping the file with the iris dataset: C:\\Users\\SOSSupport\\iris file1.csv, let’s copy it as well.

 

#Copying file

shell(“copy c:\\Users\\SOSSupport\\iris_file1.csv iris_file1_copy.csv”)

 

as well as using the parameterized shell function:

 

orig_file <- “c:\\Users\\SOSSupport\\iris_file1.csv”

copy_file <- “iris_file1_copy1.csv”

command <- “copy”

 

cmd_command <- paste(command, orig_file, copy_file)

shell(cmd_command)

 

Examine your files now.

 

3.4. Ping

We may use ping CMD directly because it is provided with the sys.which() method.

 

URL <- ‘xxxx.xxxx.com’

 

cmd_command <- “Ping”

cmd_args <- c(‘-n 1′, URL)

 

system2(command=cmd_command,

args=cmd_args,

stdout=TRUE,

stderr=TRUE,

wait = TRUE)

 

And, because we’ll be checking a lot of URLs, let’s make an empty data.frame to hold the results and a function to traverse over the list.

 

URLs <- c(“google.com”, “xxxx.xxxx.com”, “youtube.com”)

 

#empty dataframe

df_rr <- data.frame(URL = character(),

reply = character(),

package = character(),

stringsAsFactors=FALSE)

 

ping_fn <- function(url) {

system2(“ping”,c(url,’ -n 1′),

stdout=TRUE,

stderr=TRUE)

}

 

for (i in 1:length(URLs)){

site <- print(URLs[i])

rr <- ping_fn(site)

temp <- data.frame(URL=rr[2], reply=rr[3], package=rr[6])

df_rr <- rbind(df_rr, setNames(temp, names(df_rr)))

}

 

head(df_rr)

 

and the outcome is bound in a single data.frame:

 

3.5. Systeminfo

 

Assume you want information about the system in addition to the R environment. Some R functions may be found here:

 

# R

R.Version()

Sys.info()

.Platform

 

 

And they’re all incredibly useful. However, if you require Systeminfo CMD information in your R IDE environment, save it in data.frame and use the system2() function.

 

# Using system2

 

cmd_command <- “systeminfo”

rr <- system2(command=cmd_command,

stdout=TRUE,

stderr=TRUE,

wait = TRUE)

 

and obtaining the outcome:

 

To take, for example, “System Manufacturer,” simply shift to the 13th position in the vector:

 

3.6. Checklist

Obtaining a list of all active tasks

cmd_command <- “tasklist”

rr <- system2(command=cmd_command,

stdout=TRUE,

stderr=TRUE,

wait = TRUE)

 

# getting the results into something more readable format

dd <- tibble::enframe(rr)

stack(dd)[1]

 

You can obtain all more data from the data frame.

You can also terminate a specific task.

 

# kill a specific task

shell(“taskkill /F /PID 6816”)

 

got the following response: “SUCCESS: Sent termination signal to process with PID 6816.”

 

3.7 Ipconfig / netstat 3.7

The task is the same whether you want the list of IpConfig information or all of the netstat information:

 

cmd_command <- “netstat”

rr <- system2(command=cmd_command,

stdout=TRUE,

stderr=TRUE,

wait = TRUE)

 

and tibble for storing the results:

 

dd <- tibble::enframe(rr)

 

and the outcomes are the same as in CMD:

 

CMD command

  1. Finally,

When crunching figures and wrangling data, using CMD in R IDE will almost certainly not be your daily driver. However, when you need to work intimately with your files, datasets, system, or tasks, system2 and shell functions are unbeatable.

 

 

 

 

Good luck with your R-coding

 

You might find this article interesting too!: 6 Discontinued Technology Tools You Should Not Be Using Any Longer



Verified by MonsterInsights