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

为何R使用endsWith匹配字符串后缀时所有行均被判定为以'e'结尾?

问题原因

你在调用endsWith()函数时,误将数据框的列名variable用双引号包裹,导致R没有读取variable列的实际取值,而是对固定字符串"variable"进行后缀判断。字符串"variable"的末尾字符恰好为e,因此所有行都命中了第二个判断分支,统一返回Late。

修复方案

直接移除endsWith()第一个参数的引号即可,修正后代码如下:

gene_CNS <- melt(gene_CNS)
gene_CNS <- mutate(gene_CNS, timepoint = case_when(
  endsWith(variable, "k") ~ "Peak",
  endsWith(variable, "e") ~ "Late",
  endsWith(variable, "l") ~ "Preclinical",
  endsWith(variable, "t") ~ "Onset"
))

更稳妥的优化方案

如果你的variable列取值末尾固定是四个时间点关键词之一,也可以直接用字符串提取的方式生成新列,避免单字符判断可能出现的匹配冲突,代码如下:

library(stringr)
library(dplyr)
library(reshape2)

gene_CNS <- melt(gene_CNS) %>%
  mutate(timepoint = str_extract(variable, "(Late|Peak|Preclinical|Onset)$"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 06:15:05