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

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

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:

  1. library(dplyr)
  2. merged_data <- Data %>%
  3. left_join(Data_new, by = c("ID", "Treatment")) %>%
  4. mutate(Value = coalesce(Value.y, Value.x)) %>%
  5. 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:

  1. Data &lt;- data.frame(ID = c(&quot;Gfa&quot;,&quot;Gfa&quot;,&quot;Gfa&quot;,&quot;Pka&quot;,&quot;Pka&quot;,&quot;Pka&quot;),
  2. Treatment = c(&quot;Control&quot;,&quot;T1&quot;,&quot;T2&quot;,&quot;Control&quot;,&quot;T1&quot;,&quot;T2&quot;),
  3. Value = c(3,4,6,2,9,7))
  4. Data_new &lt;- data.frame(ID = c(&quot;Gfa&quot;,&quot;Pka&quot;,&quot;Pka&quot;),
  5. Treatment = c(&quot;Control&quot;,&quot;Control&quot;,&quot;T2&quot;),
  6. 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:

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

And here is the translated result:

  1. 结果
  2. ID Treatment Value
  3. 1 Gfa 控制 5
  4. 2 Gfa T1 4
  5. 3 Gfa T2 6
  6. 4 Pka 控制 2
  7. 5 Pka T1 9
  8. 6 Pka T2 8
英文:
  1. library(dplyr)
  2. Data %&gt;%
  3. rows_update(Data_new, by = c(&quot;ID&quot;, &quot;Treatment&quot;))
  4. Result
  5. ID Treatment Value
  6. 1 Gfa Control 5
  7. 2 Gfa T1 4
  8. 3 Gfa T2 6
  9. 4 Pka Control 2
  10. 5 Pka T1 9
  11. 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:

确定