stringr::str_split_n是否可用?求提取文件名内容的替代方案
First, to clear up your error: str_split_n() was deprecated in stringr version 1.4.0 and has since been removed from the package. The purpose-built replacement is str_split_i(), which does exactly what you need with a more intuitive syntax. That said, if you want to use str_split() directly as you asked, I’ve got you covered with two solid approaches.
Option 1: Use str_split_i() (Recommended)
This is the simplest and most modern way to get your desired substrings—it’s the official replacement for the old str_split_n() function:
library(stringr) library(readxl) library(dplyr) filename <- 'Income Statement Dax 2020-03-31.xlsx' # Extract first and third space-separated parts file <- str_split_i(filename, " ", 1) sheet <- str_split_i(filename, " ", 3) # Read the Excel file as intended dmap <- read_excel(file, sheet = sheet) %>% ungroup()
Option 2: Use str_split() with Indexing
If you prefer to stick with str_split(), you can convert the split result into a matrix (using simplify = TRUE) and index directly into it:
library(stringr) library(readxl) library(dplyr) filename <- 'Income Statement Dax 2020-03-31.xlsx' # Split filename into a matrix of space-separated parts split_parts <- str_split(filename, " ", simplify = TRUE) # Grab the first and third elements file <- split_parts[1] sheet <- split_parts[3] # Proceed with reading the file dmap <- read_excel(file, sheet = sheet) %>% ungroup()
Alternatively, if you don’t use simplify = TRUE, you can access the list elements directly:
split_parts <- str_split(filename, " ")[[1]] file <- split_parts[1] sheet <- split_parts[3]
Both methods will correctly assign file <- 'Income' and sheet <- 'Dax', so your read_excel() call will work exactly as you want it to.
内容的提问来源于stack exchange,提问作者CloverCeline

