如何在R中覆盖/替换特定行?

huangapple go评论88阅读模式
英文:

How to overwrite/replace specific rows in R?

问题

You can merge the Data_new to Data and overwrite the old values using R. Here's an example of how to do it:

library(dplyr)

merged_data <- Data %>%
  left_join(Data_new, by = c("ID", "Treatment")) %>%
  mutate(Value = coalesce(Value.y, Value.x)) %>%
  select(ID, Treatment, Value)

This code uses the dplyr package to left join Data_new to Data based on the "ID" and "Treatment" columns and then uses mutate to choose the new values if they exist (Value.y) or keep the old values (Value.x). Finally, it selects the desired columns.

英文:

I have a dataset containing some data obtained after a correction that should be merged with the primary dataset. I need a way to overwrite the old values with the new ones, but I don't know how.

Here is an example of what I have:

Data &lt;- data.frame(ID = c(&quot;Gfa&quot;,&quot;Gfa&quot;,&quot;Gfa&quot;,&quot;Pka&quot;,&quot;Pka&quot;,&quot;Pka&quot;),
                Treatment = c(&quot;Control&quot;,&quot;T1&quot;,&quot;T2&quot;,&quot;Control&quot;,&quot;T1&quot;,&quot;T2&quot;),
                Value = c(3,4,6,2,9,7))
                         
Data_new &lt;- data.frame(ID = c(&quot;Gfa&quot;,&quot;Pka&quot;,&quot;Pka&quot;),
                Treatment = c(&quot;Control&quot;,&quot;Control&quot;,&quot;T2&quot;),
                Value = c(5,2,8))    

How can I merge the Data_new to the Data, overwriting only the new values?

答案1

得分: 4

Sure, here is the translated code:

library(dplyr)
Data %>%
  rows_update(Data_new, by = c("ID", "Treatment"))

And here is the translated result:

结果

   ID    Treatment    Value
1   Gfa    控制         5
2   Gfa    T1          4
3   Gfa    T2          6
4   Pka    控制         2
5   Pka    T1          9
6   Pka    T2          8
英文:
library(dplyr)
Data %&gt;%
  rows_update(Data_new, by = c(&quot;ID&quot;, &quot;Treatment&quot;))


Result

   ID Treatment Value
1 Gfa   Control     5
2 Gfa        T1     4
3 Gfa        T2     6
4 Pka   Control     2
5 Pka        T1     9
6 Pka        T2     8

huangapple
  • 本文由 发表于 2023年3月21日 02:23:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定