在R中的两个条件下合并两列
我正在尝试将两列合并为一列 挑战在于,我只想在两个条件下将它们结合在一起在R中的两个条件下合并两列,r,dplyr,R,Dplyr,我正在尝试将两列合并为一列 挑战在于,我只想在两个条件下将它们结合在一起 如果工资栏有什么内容,我们不加入 如果comp列没有货币符号(),这意味着没有数值,则它们不会合并 我第一次尝试了paste(),但我认为这不是正确的情况,它也没有连接两个数据帧,因为它们只是同一数据帧中的两列。有没有办法实现这个条件连接 数据集: salary comp 19
- 如果工资栏有什么内容,我们不加入李>
- 如果comp列没有货币符号
),这意味着没有数值,则它们不会合并(
salary comp
19 £9.18 per hour <NA>
20 £35,000 to £50,000 per year Self employed, Commission Only
21 £29,000 to £30,000 per year <NA>
22 £20,000 to £35,000 per year <NA>
23 £29,000 to £31,000 per year <NA>
24 £65 to £80 per day <NA>
25 £65 to £75 per day Opportunity to become a permanent role.
26 <NA> <NA>
27 <NA> £18,000 + Bonus & Benefits
28 <NA> NMW + Overtime and Bonus
29 <NA> Depending on experience
30 <NA> £21,892 - £24,157 pa
31 <NA> £38,890 -£44,503 per annum
预期产出:
salary comp
19 £9.18 per hour <NA>
20 £35,000 to £50,000 per year Self employed, Commission Only
21 £29,000 to £30,000 per year <NA>
22 £20,000 to £35,000 per year <NA>
23 £29,000 to £31,000 per year <NA>
24 £65 to £80 per day <NA>
25 £65 to £75 per day Opportunity to become a permanent role.
26 <NA> <NA>
27 £18,000 + Bonus & Benefits £18,000 + Bonus & Benefits
28 <NA> NMW + Overtime and Bonus
29 <NA> Depending on experience
30 £21,892 - £24,157 pa £21,892 - £24,157 pa
31 £38,890 -£44,503 per annum £38,890 -£44,503 per annum
salary comp
每小时19英镑9.18英镑
20.自营职业者每年35000至50000英镑,仅佣金
21每年29000至30000英镑
22每年20000至35000英镑
23每年29000至31000英镑
24每天65至80英镑
25每天65至75英镑成为永久性角色的机会。
26
27 18000英镑+奖金和福利18000英镑+奖金和福利
28 NMW+加班费和奖金
29取决于经验
30 21892英镑-24157英镑/年21892英镑-24157英镑/年
31每年38890-44503英镑每年38890-44503英镑
联接涉及两个不同的表,它们根据某个键合并在一起。您的预期输出只是根据某些条件替换列salary中的值,这可以通过简单的mutate
:
dataset %>%
mutate(salary = if_else(is.na(salary) & grepl(pattern = "£", x=comp), comp, salary))
这应该可以做到
str_detect()
内部ifelse()
来自{stringr}
。如果这是您需要的,请告诉我。:-)
库(tidyverse)
df%
变异(salary=ifelse(is.na(salary)和str_detect(comp,”),comp,salary))
dataset %>%
mutate(salary = if_else(is.na(salary) & grepl(pattern = "£", x=comp), comp, salary))
library(tidyverse)
df <- structure(list(salary = c("£9.18 per hour", "£35,000 to £50,000 per year",
"£29,000 to £30,000 per year", "£20,000 to £35,000 per year",
"£29,000 to £31,000 per year", "£65 to £80 per day", "£65 to £75 per day",
NA, NA, NA, NA, NA, NA), comp = c(NA, "Self employed, Commission Only",
NA, NA, NA, NA, "Opportunity to become a permanent role.", NA,
"£18,000 + Bonus & Benefits", "NMW + Overtime and Bonus", "Depending on experience",
"£21,892 - £24,157 pa", "£38,890 -£44,503 per annum")), row.names = 19:31, class = "data.frame")
as_tibble(df) %>%
mutate(salary = ifelse(is.na(salary) & str_detect(comp, "£"), comp, salary))