如何在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.
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:
| Eqpmnt | Value |
|---|---|
| 501 | 10 |
| 602 | 20 |
| 504 | 40 |
| 606 | 60 |
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

