根据R中字符串的结尾创建新列

时间:2018-03-29 03:47:44

标签: r

我想根据字符串的结尾创建一个新列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")

4 个答案:

答案 0 :(得分:3)

library(tidyverse)

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

答案 1 :(得分:2)

library(dplyr)
library(stringr)
stack.df %>% mutate(Trial = ifelse(str_sub(Trtmt,-1)=="2", 2, 1))

答案 2 :(得分:2)

以下是str_extract

的一个选项
library(stringr)
library(data.table)
setDT(stack.df)[, Trial := pmax(as.numeric(str_extract(Trtmt, "\\d+$")), 1, na.rm = TRUE)]

答案 3 :(得分:1)

您可以使用substr(stack.df$Trtmt,nchar(stack.df$Trtmt)-1,nchar(stack.df$Trtmt))

获取最后一个字符

就像你说的那样,从那里开始很简单: - )