gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:43:19 24 4
gpt4 key购买 nike

我想根据字符串的结尾创建一个新列 Trial。例如,以数字 2 结尾的字符,如 A3-H2A9-H2 将被视为 Trial 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com