r - 在函数中更改小标题的元素
问题描述
我的 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)
}
但这不会改变产品小标题。
任何有关如何更有效地执行此操作的建议将不胜感激。
解决方案
像这样的东西怎么样:
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
这里的关键是
- 存储
words
在list
与列名匹配的名称中produce
, produce
从宽转换为长,并且- 正则表达式匹配来自名称的列中的条目与从长到宽重新整形数据之前
key
的匹配条目。words
推荐阅读
- ios - 如何将 IBOutlet 值从视图传递到 VIPER iOs 中的交互器?
- ios - 在 Swift 4 上调整 UIImage 视图的大小
- ember.js - 升级 Ember 时出现未知的全局错误
- elasticsearch - 在多/所有弹性搜索嵌套字段中动态搜索
- apache-camel - 根据找到的文件数量,使用 Apache Camel 将文件移动到不同的目录
- vba - VBA认为整数是对象
- pyspark - 如何仅使用 pyspark 函数查找日期
- vue.js - 在vue js中动态添加的字段内添加动态添加的字段?
- paperjs - Configure style of auto-drawn bounding box/selection outlines
- javascript - 如何提取 React 库以分离包?