R getwd() and setwd() Functions - Working Directory

R 语言实例R Language Examples

R getwd() function is used to get the current working directory, and setwd() is used to set the working directory.

The working directory refers to the default path where R reads and writes files.

The syntax of the two functions is as follows:

getwd()
setwd(dir)

Parameter Description:

  • dirNew working directory path (string).

Examples

# Get the current working directory
current_dir <- getwd()
print(paste("Current working directory:", current_dir))

# View directory contents
print("List of files in the directory:")
print(list.files())

# Set working directory (example)
# setwd("/Users/username/projects/example")

# View R's installation directory
print(paste("R installation directory (R.home):", R.home()))

Executing the above code will display the current R working directory and file list.

When reading or writing files, if you provide only the file name (without the path), R will look for the file in the current working directory. To ensure the code is portable, it is recommended to set the correct working directory first.

R 语言实例R Language Examples

Other Extensions