简体   繁体   中英

R: file.path does not output correct subdirectory

I have a directory called "DIR." In this directory are two folders called "programs," which contain R scripts and "data," which contain the .csv files I want to load.

My working directory is set to "C:/User/DIR/programs/processing" and I want to load a file called "flowers.csv" from the "data" folder. ("C:/User/DIR/data/flowers.csv").

I am trying to use the file.path function along with the "../" to load from the data folder, but it keeps giving me the wrong file path.

    dir.root <- setwd("C:/User/DIR/programs/processing")
    dir.in <- file.path(dir.root, "../raw")

Gives me

    > dir.in
    [1] "\\\\C:/User/DIR/programs/processing/../raw"

Instead of what I want "\\\\\\\\C:/User/DIR/raw/"

When I use

    read.csv("../raw/flowers.csv")

I get an error that says

    Error in file(file, "rt") : cannot open the connection
    In addition: Warning message:
    In file(file, "rt") : cannot open file '../raw/flowers.csv': No such file 
    or directory

Can anyone please help me understand what is going on? Thank you!

使用normalizePath将文件路径转换为规范形式。

dir.in <- normalizePath(file.path(dir.root, "../raw"))

You are setting dir.root to the wrong path. setwd() doesn't return the path you set, it returns the previous path (so you can return to it later if you want).

Use this code to do what you want:

olddir <- setwd("C:/User/DIR/programs/processing")
dir.root <- getwd()
dir.in <- file.path(dir.root, "../raw")

You can also call normalizePath(dir.in) as @chandra said, but that is not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM