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

R语言按规则拆分数据框列:提取文本与末尾数字

Hey there! Let's get that comment-and-score split working properly.

The issue with your original separate code is that the regex " (?=[^ ]+$)" only targets the final single space where the following content has no spaces. This might fail if there are edge cases (like extra spaces before the score, or if your text has trailing punctuation before the space+score). A more reliable approach is to use tidyr::extract, which lets you directly capture the text and score groups with a regex, rather than splitting on a delimiter.

Here's the fix:

library(dplyr)
library(tidyr)

# Your original dataset
dataset <- data.frame(Comments=c('Wow... Loved this place. 1','Crust is not good. 0','Not tasty and the texture was just nasty. 0'))

# Extract text and score
dataset_clean <- dataset %>%
  extract(
    Comments, 
    into = c("Comment", "Score"), 
    regex = "(.*?)\\s*(\\d+)$",  # Capture text, then optional spaces, then trailing digits
    remove = TRUE
  ) %>%
  mutate(Score = as.integer(Score))  # Convert score to numeric type

# View the result
dataset_clean

Running this will give you:

Comment Score
1          Wow... Loved this place.     1
2               Crust is not good.     0
3 Not tasty and the texture was just nasty.     0

How the regex works:

  • (.*?): Non-greedily captures all text up until the next part (avoids accidentally grabbing the score digits)
  • \\s*: Matches any number of spaces (including zero, though your examples have one) between the text and score
  • (\\d+)$: Captures one or more digits at the very end of the string

If you still prefer using separate, you can adjust the regex to target one or more spaces before trailing digits, and add extra = "merge" to handle any unexpected spaces in the text:

dataset %>%
  separate(
    Comments, 
    into = c("Comment", "Score"), 
    sep = "\\s+(?=\\d+$)",  # Match one+ spaces before trailing digits
    extra = "merge"
  ) %>%
  mutate(Score = as.integer(Score))

This will also give you the same clean split.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:14:39