0

I am trying to create a new column with information from another column. For example, I want "Neutrophil_A0Late" to have "Late" in a new column, and "Neutrophil_A0Peak" to have "Peak" in the new column. My current code is:

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

and it spits out:

   X1                         variable       value timepoint
1   Mertk               Neutrophils_A0Late 0.008430985      Late
2   Mertk              Neutrophils_A0Onset 0.000000000      Late
3   Mertk               Neutrophils_A0Peak 0.000000000      Late
4   Mertk        Neutrophils_A0Preclinical 0.000000000      Late

Clearly it thinks all of my "variable" entries end in "e", and I'm not sure why. Can anyone help? Please let me know if you need any more information.

  • 6
    Because you have "variable" in quotes and that string ends in "e". If you want to use the column, do not use quotes. For example `endsWith(variable, "k")` – MrFlick Jun 25 '21 at 16:41
  • Do all your entries in `variable` begin with `"Neutrophil_A0"`, or with some common format? If so, these could likely be handled extensibly in a single line, using a `mutate()` and regex. – Greg Jun 25 '21 at 16:44
  • When I try removing the quotes around variable, I end up with this error: Error: Problem with `mutate()` input `timepoint`. x non-character object(s) ℹ Input `timepoint` is `case_when(...)`. – Ashley Munie Jun 25 '21 at 16:47
  • 2
    Then it sounds like your "variable" column is probably a factor rather than a character value and `endsWith` doesn't automatically convert to character. Are you suing R 4.0 or newer? Normally you have to explictly set to factor now. But you can do `endsWith(as.character(variable), "k")` to change it back, or you could transform the column once before doing all those checks – MrFlick Jun 25 '21 at 16:51
  • Thank you!!! The as.character function worked! – Ashley Munie Jun 25 '21 at 16:53
  • 2
    If that comment solved your question you can post an answer incorporating it ...[ – Ben Bolker Jun 25 '21 at 17:44
  • Given your data, this would be simpler: `gene_CNS$timepoint <- gsub("Neutrophils_A0", "", gene_CNS$variable)`. – dcarlson Jun 26 '21 at 21:48

0 Answers0