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

如何将data frame中factor类型的Well and Depth列拆分为两列并插入指定位置

Solution for Extracting Text and Numeric Parts & Inserting Columns

Got it, let's work through this problem to get exactly what you need—inserting two new columns between your "Well and Depth" factor column and the "Mean" column, with the text before the numbers and the numeric values extracted separately.

Step 1: Load Required Package

We'll use the tidyverse suite (specifically dplyr for column manipulation and stringr for string extraction) since it makes this task straightforward:

library(tidyverse)

Step 2: Extract Text/Numeric Parts & Adjust Column Position

First, we'll convert the factor column to character (to avoid issues with string operations on factor levels), then extract the two parts, and finally move the new columns to the right spot.

Here's the code with clear explanations:

df <- df %>%
  # Convert the factor column to character for reliable string matching
  mutate(`Well and Depth` = as.character(`Well and Depth`)) %>%
  # Extract text before the first numeric character
  mutate(Text_Part = str_extract(`Well and Depth`, "^\\D+"),
         # Extract all numeric characters and convert to numeric type
         Number_Part = as.numeric(str_extract(`Well and Depth`, "\\d+"))) %>%
  # Relocate the new columns to sit between "Well and Depth" and "Mean"
  relocate(Text_Part, Number_Part, .after = `Well and Depth`, .before = "Mean")

Alternative for Edge Cases

If some entries in "Well and Depth" start with numbers (no leading text) or have mixed non-numeric characters, this adjusted version returns empty strings instead of NA for text parts:

df <- df %>%
  mutate(`Well and Depth` = as.character(`Well and Depth`)) %>%
  # Remove trailing numbers to isolate the text part
  mutate(Text_Part = str_replace(`Well and Depth`, "\\d+$", ""),
         # Remove leading non-numeric characters to isolate the number part
         Number_Part = as.numeric(str_replace(`Well and Depth`, "^\\D+", ""))) %>%
  relocate(Text_Part, Number_Part, .after = `Well and Depth`, .before = "Mean")

Breakdown of Key Functions

  • str_extract(Well and Depth, "^\\D+"): Matches all non-numeric characters from the start of the string up to the first number.
  • str_extract(Well and Depth, "\\d+"): Captures all consecutive numeric characters in the string.
  • relocate(...): Precisely places the new columns right after "Well and Depth" and before "Mean"—no need to count column positions manually!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:33:49