首页 > 解决方案 > 在函数中更改小标题的元素

问题描述

我的 tibble 中有一组字符串变量,我想根据它们的字符串内容将它们重新编码为特定的整数。我的代码如下所示:

library(tidyverse)

a<-c("this string says apple", "this string says banana", "this string says carrot", "this string says apple")
b<- c("this string says pumpkin", "this string says radish", "this string says eggplant", "this string says radish")
produce <- tibble(a,b)

a_words <- c("apple", "banana", "carrot")
b_words <- c("pumpkin", "radish", "eggplant")

my_function<-function(var,word_vec,num_vec){ 
  for (i in seq_along(word_vec)){
    var[grepl(word_vec[[i]],var)]<-num_vec[[i]]
  }
  return(var)
}

当我分别处理每个变量时,我能够得到想要的结果:

produce$a <- my_function(produce$a,a_words,1:3)
produce$b <- my_function(produce$b,b_words,1:3)

> produce
# A tibble: 4 x 2
  a     b    
  <chr> <chr>
1 1     1    
2 2     2    
3 3     3    
4 1     2  

但实际上我有几个变量要重新编码(但不是小标题中的所有变量)。我尝试了一个循环功能:

for (i in c("produce$a", "produce$b")){
  i <- my_function(i, paste0(str_replace(i,"produce$", ""),"_words"), 1:3)
}

但这不会改变产品小标题。

任何有关如何更有效地执行此操作的建议将不胜感激。

标签: r

解决方案


像这样的东西怎么样:

words <- list(
    a = c("apple", "banana", "carrot"),
    b = c("pumpkin", "radish", "eggplant"))

produce %>%
    rowid_to_column("row") %>%
    gather(key, val, -row) %>%
    rowwise() %>%
    mutate(val = map_int(words[key], ~which(str_detect(val, .x) == TRUE))) %>%
    spread(key, val) %>%
    select(-row)
## A tibble: 4 x 2
#      a     b
#  <int> <int>
#1     1     1
#2     2     2
#3     3     3
#4     1     2

这里的关键是

  • 存储wordslist与列名匹配的名称中produce
  • produce从宽转换为长,并且
  • 正则表达式匹配来自名称的列中的条目与从长到宽重新整形数据之前 key的匹配条目。words

推荐阅读