为何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
相关产品推荐
相关产品推荐

