I am reading in a bunch of files from a folder, merge them into a data frame, and then save that data frame "outside" of that folder. E.g.
我正在从一个文件夹中读取一堆文件,并将它们合并到一个数据框中,然后将数据框保存到该文件夹的“外部”。如。
# path to folder that contains files to read in:
path <- "/path/to/folder"
# read in files
files <- list.files(path, pattern = "*.csv", full.names = TRUE)
# do stuff with files
...
# safe data frame
path.2 <- "/path/to/"
write.csv2(paste0(path.2, "dat.csv"), dat)
No sweat.
没有汗水。
But I want to be able to change the value for the variable path
, without having to manually change the value for path.2
, too. I want to automatically assign path.2
the value of path
, minus the folder name, without having to tell R the name of that folder. That is, I need to trim all characters from the right end of the string in path
, until the file separator ("/").
但是我希望能够改变变量路径的值,而不必手动更改路径的值。2,太。我想自动分配路径。路径的值,减去文件夹名,而不用告诉R文件夹的名称。也就是说,我需要在路径中从字符串的右端删除所有字符,直到文件分隔符(“/”)。
Pseudocode:
伪代码:
path <- "/path/to/folder"
path.2 <- rtrim(path, to = "/")
path.2
[1] "/path/to/"
How can I go about that?
我该怎么做呢?
2 个解决方案
#1
0
Using sub
,
使用子,
sub('/([^/]*)$', '', path)
#[1] "/path/to"
Or using str_extract
from stringr
package,
或者使用str_extract from stringr包,
str_extract(path, '^(?:[^/]*/){3}')
#[1] "/path/to/"
#2
0
Something like this:
是这样的:
path <- "/path/to/folder"
paste(head(unlist(strsplit(path, "/", fixed = TRUE)), -1), collapse = "/")
# [1] "/path/to"
#1
0
Using sub
,
使用子,
sub('/([^/]*)$', '', path)
#[1] "/path/to"
Or using str_extract
from stringr
package,
或者使用str_extract from stringr包,
str_extract(path, '^(?:[^/]*/){3}')
#[1] "/path/to/"
#2
0
Something like this:
是这样的:
path <- "/path/to/folder"
paste(head(unlist(strsplit(path, "/", fixed = TRUE)), -1), collapse = "/")
# [1] "/path/to"