gpt4 book ai didi

r - 如何使用dplyr检测字符串中字符的位置

转载 作者:行者123 更新时间:2023-12-04 08:06:21 24 4
gpt4 key购买 nike

我有以下数据框:

library(tidyverse)
df <- tribble(
~sname, ~seq,
"foo", "TTAW",
"bar", "ACTN",
"qux", "AAAA"
)

df
我想要的是第三列在每一行中定位“T”的位置。
最终结果如下所示:
  sname seq  t_pos
foo TTAW 1,2
bar ACTN 3
qux AAAA 0
我怎样才能做到这一点?
我试过这个但不起作用:
df %>% 
dplyr::mutate(t_pos = paste0( list(which(strsplit(seq, "")[[1]] == "T") ) ))
正确的做法是什么?

最佳答案

您可以添加 rowwise你的尝试:

library(dplyr)

df %>%
rowwise() %>%
mutate(t_pos = toString(which(strsplit(seq, "")[[1]] == "T")))

# sname seq t_pos
# <chr> <chr> <chr>
#1 foo TTAW "1, 2"
#2 bar ACTN "3"
#3 qux AAAA ""
map_chr :
df %>% 
mutate(t_pos = purrr::map_chr(strsplit(seq, ""), ~toString(which(.x == "T"))))
并在基础 R 中:
df$t_pos <- sapply(strsplit(df$seq, ''), function(x) toString(which(x == 'T')))

关于r - 如何使用dplyr检测字符串中字符的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66203722/

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