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

是否有R函数可提取向量中最后空格与"-APPLE"间的数字?

Extracting Numbers Between Last Space and "-APPLE" in R

Got it, let's work through this problem together! You need to pull variable-length numbers that sit between the last space and the "-APPLE" suffix in each string, returning NA when "-APPLE" isn't present. Here are two reliable ways to do this in R:

Using stringr (Tidyverse)

The stringr package makes string manipulation super intuitive. We'll use str_match with a regular expression to capture the target numbers:

library(stringr)

# Your test vector
test_string <- c("ABC 2-APPLE", "123 25-APPLE", "DEF GHI 567-APPLE", "ORANGE")

# Extract the captured number group
matches <- str_match(test_string, ".*\\s(\\d+)-APPLE")[, 2]

# Convert empty matches to NA and coerce to numeric
result <- as.numeric(ifelse(is.na(matches), NA, matches))

# Check the result
result
#> [1]   2  25 567  NA

How the regex works:

  • .*\\s: Greedily matches all characters up to the last space (so we ignore any earlier spaces in the string)
  • (\\d+): Captures one or more digits (this is our target number)
  • -APPLE: Ensures we're only capturing digits that directly precede this exact suffix

Base R Approach (No Extra Packages)

If you prefer to stick with base R, you can use gregexpr and regmatches with Perl-style regular expressions:

test_string <- c("ABC 2-APPLE", "123 25-APPLE", "DEF GHI 567-APPLE", "ORANGE")

# Find all matches using lookarounds
matches <- regmatches(test_string, gregexpr("(?<=\\s)\\d+(?=-APPLE)", test_string, perl = TRUE))

# Convert matches to numeric, returning NA for no matches
result <- sapply(matches, function(x) if (length(x) == 0) NA else as.numeric(x))

result
#> [1]   2  25 567  NA

How this regex works:

  • (?<=\\s): Positive lookbehind to ensure the digits follow a space
  • \\d+: Matches one or more digits
  • (?=-APPLE): Positive lookahead to ensure the digits are immediately followed by "-APPLE"

Is there a dedicated R function for this?

There isn't a single "one-click" function specifically for this exact task, but R has a robust set of string manipulation tools (like the ones above) that let you build this logic easily. The key is using regular expressions to target the specific pattern you need.

内容的提问来源于stack exchange,提问作者Prabha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:45:42