对于循环和gsub R [英] For loop and gsub R
问题描述
我对在R的for循环中使用gsub有一个疑问.
I have a question about having a gsub in a for loop in R.
我有一个带有"sku"和"cat"列的数据框(目录),它们是来自不同来源的同一产品的sku ID和商品目录ID.
I have a dataframe (catalog) with "sku" and "cat" columns, they are a sku ID and a Catalog ID for the same product from different sources.
然后我有了一个带有sku的数据框( image_data )和图像说明(image_data).
I then have a dataframe (image_data) with sku, and image descriptions (image_data).
我想创建一个新列( new_image_description ),其中sku的所有实例都替换为 image_des 列中的相应目录号(请参见下面的内容).
I want to create a new column(new_image_description) where all instances of sku's is replaced by the corresponding catalog number (see bellow) from the column image_des.
但只能替换部分,而不能替换. 下面是一些虚拟数据.
But only replaces some and other not. bellow is some dummy data.
catalog <- data.frame(sku = c('AX1', "BX2", "CX2", "DXX"),
cat = c("AL1", "AL2", "AL3", "AL4"))
image_data <- data.frame(sku = c("CX2", "AX1", "BX2"),
image_des = c("CX2 is a good product", "AX1 is not bad", "BX2 is great as well as DXX"))
image_data$new_image_description <- NA
for (i in 1:nrow(catalog)) {
image_data$new_image_description <- gsub(as.character(catalog$sku[i]), as.character(catalog$cat[i]), image_data$image_des)
}
我希望能提供任何可以解释为什么它不能替代sku的输入.
I would appreciate any input that can explain why it does not substitute the sku.
如果我单独进行,它会起作用.
If I do it individually it works.
对所有人最好
推荐答案
您可以使用 qdap::mgsub
以执行多个搜索和替换操作:
You may use qdap::mgsub
to perform multiple search and replace operations:
多个Gsub
gsub
包含搜索字词向量和替换向量或单个值.
Multiple Gsub
A wrapper forgsub
that takes a vector of search terms and a vector or single value of replacements.
请参阅R演示
> library(qdap)
> image_data$new_image_description <- mgsub(as.character(catalog$sku), as.character(catalog$cat), image_data$image_des)
> image_data
sku image_des new_image_description
1 CX2 CX2 is a good product AL3 is a good product
2 AX1 AX1 is not bad AL1 is not bad
3 BX2 BX2 is great as well as DXX AL2 is great as well as AL4
这篇关于对于循环和gsub R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!