我有一个包含名称的大型数据集(超过60.000行)。但是,写下名称的格式有所不同,并且为了提高数据质量,我需要以单一格式重新编码名称。而不是复制粘贴recode-command,我想这样做,例如,在一个循环中。我列出了所有写错的名字,以及所有相应写错的名字。
所以基本上,我想做的是: 在list1中使用名称1并在list2中替换为名称1,然后在list1中使用名称2并在list2中替换为名称2,依此类推。使用gsub似乎没什么大不了的?但是...
我似乎接近了,但是输出仍然不是我想要的。有谁知道为什么或者比我现在做的更好的解决方案?
示例
> dput(list1)
c("Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7",
"Name8", "Name9", "Name10")
> dput(list2)
c("test1", "test2", "test3", "test4", "test5", "test6", "test7",
"test8", "test9", "test10")
我添加了打印命令,以查看实际发生的情况,它似乎可以正常工作:
for (i in 1:length(list1)){
newlist <- gsub(paste0("\\<",list1[i], "\\>"), list2[i], list1)
print(i)
print(newlist[i])
}
[1] 1
[1] "test1"
[1] 2
[1] "test2"
[1] 3
[1] "test3"
[1] 4
[1] "test4"
[1] 5
[1] "test5"
[1] 6
[1] "test6"
[1] 7
[1] "test7"
[1] 8
[1] "test8"
[1] 9
[1] "test9"
[1] 10
[1] "test10"
但是当我问新列表是什么样子时:
> newlist
[1] "Name1" "Name2" "Name3"
[4] "Name4" "Name5" "Name6"
[7] "Name7" "Name8" "Name9"
[10] "test10"
此外,我尝试使用lapply并编写自己的函数...都无法实现我想要的方式:(
答案 0 :(得分:1)
在循环外定义新列表,并在循环中一次仅更改一个索引
newlist = list1
for (i in 1:length(list1)){
newlist[i] <- gsub(paste0("\\<",list1[i], "\\>"), list2[i], list1)[i]
}
答案 1 :(得分:1)
您可以使用list1
在sapply(list1, function(x) paste0("\\b",x,"\\b"))
中创建正则表达式模式,然后将模式列表以及替换列表传递到qdap::mgsub
function中:
list1 <- c("Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10")
list2 <- c("test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10")
regList1 <- sapply(list1, function(x) paste0("\\b",x,"\\b"))
qdap::mgsub(regList1, list2, "Name1 should be different. Name10, too.", fixed=FALSE)
## => [1] "test1 should be different. test10, too."
如果list1
字符向量中的项目全部由字母数字或_
字符组成,则此解决方案将起作用。否则,您还需要转义值,并以described here的方式使用PCRE regex。
答案 2 :(得分:0)
您可以使用mapply
进行此操作。
mapply(function(x, y){
gsub(paste0("\\<",x, "\\>"), y, x)
}, list1, list2)
Name1 Name2 Name3 Name4 Name5 Name6 Name7 Name8 Name9 Name10
"test1" "test2" "test3" "test4" "test5" "test6" "test7" "test8" "test9" "test10"
将unname()
包裹起来以摆脱名称。