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

R语言:提取包装规格中的数量、容量及计量单位组件

Extract Volume and UOM from Pack Vector in R

Got it, let's solve this problem step by step. You've already nailed extracting the item quantity, so let's focus on pulling out the single item volume and unit of measurement (UOM) from your pack vector using regular expressions in R.

1. Extract Single Item Volume

The volume is the numeric value immediately following the X in each string. We can target this with a regex that captures the digits right after X, ignoring any trailing characters:

pack <- c("1X7CL ML", "2X3ML CLose","24X33cl Ltront","24X1LTR CLear", "192X5cl mlow")

# Extract volume
volume <- as.numeric(gsub(".*X(\\d+).*", "\\1", pack))

How this works:

  • .*X matches any characters up to and including the X
  • (\\d+) captures one or more digits (this is our volume value)
  • .* matches any remaining characters after the volume
  • We replace the entire string with the captured digits (\\1) and convert to numeric

2. Extract Unit of Measurement (UOM)

We need to capture the first occurrence of CL, ML, or LTR (case-insensitive) in each string. Let's use your UOM vector to build a flexible regex pattern, then extract and standardize the UOM to match your expected output:

Option 1: Base R (no extra packages)

UOM <- c("CL","ML","LTR")

# Build regex pattern to match any UOM (case-insensitive)
uom_pattern <- paste(toupper(UOM), collapse = "|")

# Extract UOM, standardize to uppercase
uom <- gsub(paste0(".*(", uom_pattern, ").*"), "\\1", toupper(pack))

Option 2: Using stringr (cleaner syntax)

If you don't mind using the stringr package, this approach is more straightforward:

library(stringr)

uom <- str_extract(toupper(pack), paste(toupper(UOM), collapse = "|"))

How this works:

  • toupper(pack) converts all characters to uppercase to handle case variability (like cl, Ltr)
  • paste(toupper(UOM), collapse = "|") creates a regex pattern like CL|ML|LTR to match any valid UOM
  • str_extract pulls the first matching UOM from each string, while the base R gsub approach replaces the entire string with the captured UOM

3. Verify All Results

Let's combine all three vectors into a data frame to confirm we match your expected output:

# Quantity extraction (your existing code)
quantity <- as.numeric(gsub("(.*?)(X.*)", "\\1", pack))

# Combine into data frame
result <- data.frame(
  quantity = quantity,
  volume = volume,
  uom = uom
)

print(result)

Output:

quantity volume  uom
1        1      7   CL
2        2      3   ML
3       24     33   CL
4       24      1  LTR
5      192      5   CL

This exactly matches the expected results you listed!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:14:17