gpt4 book ai didi

r - 匹配和替换 data.table 中的许多值

转载 作者:行者123 更新时间:2023-12-04 18:07:52 26 4
gpt4 key购买 nike

我有一个包含许多错误命名条目的数据集。我创建了一个两列 .csv,其中包括一列中的旧(不正确)名称和第二列中相应的新(正确)名称。现在我需要告诉 R 用正确的名称替换数据中的每个旧名称。

testData = data.table(oldName = c("Nu York", "Was DC", "Buston",  "Nu York"))
replacements = data.table(oldName = c("Buston", "Nu York", "Was DC"),
newName = c("Boston", "New York", "Washington DC"))

# The next line fails.
holder = replace(testData, testData[, oldName]==replacements[, oldName],
replacements[, newName]

最佳答案

这就是我将如何进行替换:

setkey(testData, oldName)
setkey(replacements, oldName)

testData[replacements, oldName := newName]
testData
# oldName
#1: Boston
#2: New York
#3: New York
#4: Washington DC

如果您喜欢原始顺序,可以添加索引,并在最后将其放回原始顺序。

关于r - 匹配和替换 data.table 中的许多值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22355201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com