![](/img/trans.png)
[英]How to replace values of a character column based on the occurrence of specific strings in another column of an R data frame?
[英]R replace values of a column based on exact match of another data frame
我在 R 中有 2 個數據框
DF1
是
ColA ColB observation
123 Text1 45
234 Text2 65
345 Text3 78
DF2
是
ColumnA ColumnB metric
123 Text1 7
123 Text2 65
345 Text1 102
我想用DF2
的metric
列的值替換DF1
的observation
列,但僅用於在ColA
= ColumnA
和ColB
= ColumnB
上具有完全匹配的行。 上面的例子應該輸出以下數據幀:
ColA ColB value
123 Text1 7
234 Text2 65
345 Text3 78
這是一個基本的 R 解決方案,使用merge
+ ifelse
DF <- within(merge(DF1,DF2,by.x = c("ColA","ColB"),by.y = c("ColumnA","ColumnB"),all.x = TRUE),
value <- ifelse(is.na(metric),observation,metric))[-(3:4)]
以至於
> DF
ColA ColB value
1 123 Text1 7
2 234 Text2 65
3 345 Text3 78
使用dplyr
解決方案:
由於您沒有提供最小的可重現示例,因此我無法測試代碼...
library(dplyr)
DF1 %>%
left_join(DF2, by=("ColA"="ColumnA", "ColB"="ColumnB") %>%
mutate(value = if_else(!is.na(metric), metric, observation)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.