我想基于字符串的结尾创建一个新列Trial。例如,以数字2结尾的字符(例如A3-H2A9-H2)将被视为试验2,而未以数字结尾的字符(例如A3-HA9-H)将被视为试验1。这应该很容易ifelse语句,但是我不知道如何根据字符串的结尾进行操作。

它将是这样的:

      Plant     Trtmt
1:     SC       A3-H
2:     SC       A3-H2
3:     SC       A9-H
4:     SC       A9-H2


对此:

      Plant     Trtmt    Trial
1:     SC       A3-H       1
2:     SC       A3-H2      2
3:     SC       A9-H       1
4:     SC       A9-H2      2


真实数据:

dput(stack.df)
structure(list(Plant = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("SC",
"W"), class = "factor"), Trtmt = c("A3-H", "A3-H", "A3-H", "A3-H",
"A3-H", "A9-H", "A9-H", "A9-H", "A9-H", "A9-H", "A3-H2", "A3-H2",
"A3-H2", "A3-H2", "A3-H2", "A9-H2", "A9-H2", "A9-H2", "A9-H2",
"A9-H2")), .Names = c("Plant", "Trtmt"), row.names = c(6L, 7L,
8L, 9L, 10L, 16L, 17L, 18L, 19L, 20L, 66L, 67L, 68L, 69L, 70L,
76L, 77L, 78L, 79L, 80L), class = "data.frame")

最佳答案

library(tidyverse)

stack.df <- stack.df %>%
  mutate(Trial = ifelse(grepl("2$", Trtmt), 2, 1))

关于r - 根据R中的字符串结尾创建新列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49547708/

10-12 16:30