英文:
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 <- data.frame(ID = c("Gfa","Gfa","Gfa","Pka","Pka","Pka"),
Treatment = c("Control","T1","T2","Control","T1","T2"),
Value = c(3,4,6,2,9,7))
Data_new <- data.frame(ID = c("Gfa","Pka","Pka"),
Treatment = c("Control","Control","T2"),
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 %>%
rows_update(Data_new, by = c("ID", "Treatment"))
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论