我有一个数据框,其中一列是名称。在分析的后期阶段,我需要通过此名称列与其他数据合并,并且有一些名称因来源而异。我想使用名称->已清理名称的哈希(映射)来清理我的名称。我发现了几个使用 R 列表作为哈希的参考(例如,这个关于 SE 的问题),但我无法弄清楚如何仅在向量中的键出现时提取它们的值。例如,
> players=data.frame(names=c("Joe", "John", "Bob"), scores=c(9.8, 9.9, 8.8))
> xref = c("Bob"="Robert", "Fred Jr." = "Fred")
> players$names
[1] Joe John Bob
Levels: Bob Joe John
Run Code Online (Sandbox Code Playgroud)
虽然players$names给出了来自原始帧的名称向量,但我需要相同的向量,仅将出现的任何值xref替换为它们的等效(查找)值;我想要的结果是向量Joe John Robert。
我最接近的是:
> players$names %in% names(xref)
[1] FALSE FALSE TRUE
Run Code Online (Sandbox Code Playgroud)
这正确地表明players$names的“键”(名称)中仅存在“Bob” xref,但我无法弄清楚如何提取该名称的值并将其与向量中不属于的其他名称组合要xref根据需要。
注意:如果它不完全清楚,我对 R 还很陌生,所以如果我以错误的方式接近这个,我很高兴得到纠正,但我的核心问题本质上是如所述:我需要清理通过用已知替换替换一些传入值并保留所有其他值,在 R 中添加一些传入数据;此外,原始-> 替换的地图应存储为数据(如外部参照),而不是代码。
ifelse 在外部参照是命名向量而不是列表的情况下,这是一个更直接的解决方案。
players <- data.frame(names=c("Joe", "John", "Bob"), scores=c(9.8, 9.9, 8.8), stringsAsFactors = FALSE)
xref <- c("Bob" = "Robert", "Fred Jr." = "Fred")
players$clean <- ifelse(is.na(xref[players$names]), players$names, xref[players$names])
players
Run Code Online (Sandbox Code Playgroud)
结果
names scores clean
1 Joe 9.8 Joe
2 John 9.9 John
3 Bob 8.8 Robert
Run Code Online (Sandbox Code Playgroud)
如果外部参照是一个列表,则sapply函数可用于进行条件查找
players <- data.frame(names=c("Joe", "John", "Bob"), scores=c(9.8, 9.9, 8.8))
xref <- list("Bob" = "Robert", "Fred Jr." = "Fred")
players$clean <- sapply(players$names, function(x) ifelse( x %in% names(xref), xref[x], as.vector(x)) )
players
Run Code Online (Sandbox Code Playgroud)
结果
> players
names scores clean
1 Joe 9.8 Joe
2 John 9.9 John
3 Bob 8.8 Robert
Run Code Online (Sandbox Code Playgroud)