在逗号分隔的其他列中添加列的位置列

Add Column of Position of Column in Comma-Separated Other Column

我有这样丑陋的数据:

source_data <- data.frame(thing = c('C', 'E', 'G'), ugly_sequence_string = c('A,B,C', 'D,E,F', 'G,H,I'))

我想在 ugly_sequence_string:

中添加一个整数位置的列
target_data <- data.frame(thing = c('C', 'E', 'G'), position = c(3L, 2L, 1L))

我觉得这必须通过 strsplit(或 stringr::str_split)、dplyr::mutate 和 purrr::map 的某种组合才能实现,但我无法换行我的想法围绕着如何去做的某些方面。例如,这绝对行不通:

source_data %>% 
  dplyr::mutate(
    position = which(stringr::str_split(ugly_sequence_string, ',') == thing)
  )

我试过将它分解成一个函数(使用 unlist() 和 as.list() 的各种组合,使其成为一种令人满意的格式),但它看起来像这样可能是一件容易的事,我只是不 grokking。建议?

transform(d,here=mapply(function(x,y)regexpr(x,gsub(",","",y))[[1]],d$thing,d$ugl))
  thing ugly_sequence_string here
C     C                A,B,C    3
E     E                D,E,F    2
G     G                G,H,I    1

甚至:

 here=mapply(function(x,y)match(x,strsplit(y,",")[[1]]),d[,1],d[,2])

这是一个选项:

source_data$index <- sapply(1:nrow(source_data), function(x) {which(
       strsplit(source_data$ugly_sequence_string[x],',')[[1]]==source_data$thing[x])})

输出:

  thing ugly_sequence_string index
1     C                A,B,C     3
2     E                D,E,F     2
3     G                G,H,I     1

希望对您有所帮助!

一种方法是使用基础 rstringrmapply 作为:

source_data <- data.frame(thing = c('C', 'E', 'G'), 
                 ugly_sequence_string = c('A,B,C', 'D,E,F', 'G,H,I'))

library(stringr)
#Function to perform search
find_thing <- function(x, y){
  which(stringr::str_split(x, ',') [[1]] == y)
}

source_data$position <- mapply(find_thing, 
                               source_data$ugly_sequence_string, source_data$thing)

Result:
> source_data
  thing ugly_sequence_string position
1     C                A,B,C        3
2     E                D,E,F        2
3     G                G,H,I        1