r - Is there a selective replace function? Should it be done using a If statement or For loop?
问题描述
I am relatively new to R. I need some help with more of a find and replace function but it is a bit more selective.
The example datasets I am using can be derived through:
name_1 <- c("Madeline","Maximillian","Maxon","Mad","Marvin")
value <- c(2.3,3.4,7.5,1.9,16.2)
scoreboard_table <- data.frame(name_1,value)
name_2 <- c("Madeline","Maximillian","Maxon","Mad")
nickname_1 <- c("Mad","Max","M","N/A")
nickname_2 <- c("Madine","Maxim","N/A","N/A")
nickname_table <- data.frame(name_2,nickname_1,nickname_2)
I want to replace the name of the scoreboard table with the second nickname. In that case, it would result in scoreboard_table to turn into:
name_1 <- c("Madine","Maxim","Maxon","Mad","Marvin")
value <- c(2.3,3.4,7.5,1.9,16.2)
scoreboard_table <- data.frame(name_1,value)
I am sure if doing a for loop would be easier or making an if, else statement. How should I go about this overall?
Thank you for the help in advance. It is really appreciated.
解决方案
You can perform a join and use coalesce
to get names from nickname_2
.
library(dplyr)
left_join(scoreboard_table, nickname_table, by = c('name_1' = 'name_2')) %>%
transmute(name_1 = coalesce(nickname_2, name_1),
value) -> scoreboard_table
scoreboard_table
# name_1 value
#1 Madine 2.3
#2 Maxim 3.4
#3 Maxon 7.5
#4 Mad 1.9
#5 Marvin 16.2
If they are not already change the "N/A"
values to real NA
in your data.
nickname_table[nickname_table == 'N/A'] <- NA
推荐阅读
- c# - C# Razor List to JSON:按键获取值
- html - 图像作为cshtml中的超链接
- java - java.lang.ClassCastException:通过 Selenium 执行测试时,java.base/java.lang.String 无法转换为 org.openqa.selenium.WebElement
- bash - 使用来自另一个函数的用户提示调用 bash 函数
- apache-camel - 向 PowerBI REST Endpoint 发送 POST 请求时出现 Apache Camel 状态代码 401
- c++ - 隐藏由 WinAPI 调用创建的窗口
- divide-and-conquer - 使用分治法查找每个子数组的最大和最小元素的差之和的程序
- java - 使用h2方言进行测试时,Spring正在设置mysql方言
- code-splitting - React 通用组件在连接到 store 时抛出错误
- python - 如何计算文本文件中重复单词的数量?