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

如何在R中筛选指定匹配行并修正Eqpmnt列设备名称?

Hey there! I've got you covered on this R dataframe manipulation task. Let's walk through how to get your desired result step by step.

Solution in R

First, let's start with some sample data to test our code (you can replace this with your actual dataframe):

# Sample dataframe
df <- data.frame(
  Eqpmnt = c("501R", "602", "403", "504R", "705", "606R"),
  Value = c(10, 20, 30, 40, 50, 60)
)

Option 1: Using dplyr & stringr (Clean, Readable Code)

This is my recommended approach since the syntax is intuitive and easy to follow. First, make sure you have the packages installed and loaded:

install.packages(c("dplyr", "stringr")) # Only run once
library(dplyr)
library(stringr)

Now we can chain together the filtering and string modification steps:

target_df <- df %>%
  # Keep rows where Eqpmnt starts with 5 or 6
  filter(str_detect(Eqpmnt, "^[56]")) %>%
  # Remove trailing "R" from equipment names
  mutate(Eqpmnt = str_replace(Eqpmnt, "R$", ""))

Quick breakdown of the regex:

  • ^[56]: The ^ anchors the match to the start of the string, and [56] matches either a 5 or 6.
  • R$: The $ anchors the match to the end of the string, so we only target "R" characters that are at the very end of the equipment name.

Option 2: Base R (No External Packages)

If you prefer not to use additional packages, you can achieve the same result with base R functions:

# Step 1: Filter rows where Eqpmnt starts with 5 or 6
filtered_rows <- grepl("^[56]", df$Eqpmnt)
filtered_df <- df[filtered_rows, ]

# Step 2: Remove trailing "R" from Eqpmnt column
filtered_df$Eqpmnt <- sub("R$", "", filtered_df$Eqpmnt)

# Your final dataframe
target_df <- filtered_df

Check the Result

After running either of the above code blocks, your target_df will look like this:

EqpmntValue
50110
60220
50440
60660

Perfect—this matches exactly what you needed: only rows starting with 5 or 6, and any trailing "R" stripped from the equipment names.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:03:03