在R语言中基于CODON列特定值提取行数据的技术咨询
Got it, let's break down why your original code returned an empty dataframe, then fix it with straightforward solutions.
Why Your Original Code Failed
Your line od_lig <- filter(odor_lig, CODON== "$-2") is looking for rows where the entire CODON string exactly matches $-2—but your actual CODON values are MET-2, LYS-2, etc. Since none of your rows have CODON equal to $-2, you get no results.
Solution 1: Use Regular Expressions with grepl()
You can use base R's grepl() function to check if the CODON string ends with -2. The regex -2$ tells R to match any string that ends with -2 ($ is a regex anchor for the end of a string).
library(dplyr) # Filter rows where CODON ends with "-2" od_lig <- filter(odor_lig, grepl("-2$", CODON))
Solution 2: Use stringr::str_ends() (More Readable)
If you're using the tidyverse, the stringr package has a dedicated function for checking suffixes: str_ends(). It's more intuitive than writing regex directly:
library(dplyr) library(stringr) # Check if CODON ends with "-2" and filter od_lig <- filter(odor_lig, str_ends(CODON, "-2"))
Bonus: Base R Alternative (No dplyr)
If you prefer not to use dplyr, you can use base R's subset() function with the same grepl() check:
od_lig <- subset(odor_lig, grepl("-2$", CODON))
Quick Note
Double-check that your column name is spelled correctly (CODON, not lowercase codon or a typo) and that there are no hidden spaces in your CODON values. If there are leading/trailing spaces, add str_trim(CODON) inside the check to clean them first.
内容的提问来源于stack exchange,提问作者sidrah maryam

