You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

stringr::str_split_n是否可用?求提取文件名内容的替代方案

Solution for Extracting Substrings from Your Filename

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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:22:47