gpt4 book ai didi

r - 如何有效地进行字符串的成对替换

转载 作者:行者123 更新时间:2023-12-02 21:59:00 28 4
gpt4 key购买 nike

我有一个系数名称列表,我想用更好的标签替换技术术语。函数调用如下所示

replace.pairwise(list("coef1","coef2"),
coef1="price",coef2="eventdummy", coef3="income")

并且应该返回

"price"      "eventdummy"

最佳答案

这很容易。将您的翻译存储在命名向量中:

translations <- c(coef1 = "price", coef2 = "eventdummy", coef3 = "income")

然后使用[:

vector.of.strings <- c("coef1","coef2")

translations[vector.of.strings]
# coef1 coef2
# "price" "event dummy"

如您所见,输出也是一个命名向量。如果名称对您来说是个问题,您可以执行 unname(translations[vector.of.strings])

此外,如果您的原始姓名位于示例中的列表中,则您已经了解unlist:

translations[unlist(list.of.strings)]

重要提示:如果您的所有原始名称都有替换,则上述所有内容都可以正常工作。如果情况并非如此,而您只想修改那些可替换的名称,则可以执行以下操作:

ifelse(is.na(translations[vector.of.strings]),
vector.of.strings,
translations[vector.of.strings])

关于r - 如何有效地进行字符串的成对替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17252059/

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