英文:
How to replace all df selected rows with one specific row in R
问题
所以我正在尝试根据另一个数据框来更改数据框中的所有行值,如下所示:
df1:
PROD | Num | Comment | --- |
---|---|---|---|
1.C.232 | --- | ||
1.C.231 | --- | ||
1.C.433 | --- |
df2:
PROD | Num | Comment | --- |
---|---|---|---|
1.C.1612 | 1 | my cor. | --- |
期望的输出:
PROD | Num | Comment | --- |
---|---|---|---|
1.C.1612 | 1 | my cor. | --- |
1.C.1612 | 1 | my cor. | --- |
1.C.1612 | 1 | my cor. | --- |
我尝试了以下方法,但它只是用一行替换了所有内容:
df1[, c("PROD", "Num", "Comment")] <- df2[, c("PROD", "Num", "Comment")]
英文:
so i'm trying to change all the row values in the dataframe based on another dataframe like this:
df1:
PROD | Num | Comment | --- |
---|---|---|---|
1.C.232 | --- | ||
1.C.231 | --- | ||
1.C.433 | --- |
df2:
PROD | Num | Comment | --- |
---|---|---|---|
1.C.1612 | 1 | my cor. | --- |
desired output:
PROD | Num | Comment | --- |
---|---|---|---|
1.C.1612 | 1 | my cor. | --- |
1.C.1612 | 1 | my cor. | --- |
1.C.1612 | 1 | my cor. | --- |
I tried the following, but it just replaces everything with one row:
df1[, c("PROD", "Num", "Comment")] <- df2[, c("PROD", "Num", "Comment")]
答案1
得分: 3
这只是一个简单的示例:
df1[] <- df2
以下是一个完整的演示示例:
df1 <- data.frame(Prod = c('1.C.232', '1.C.231', '1.C.433'),
Num = rep('', 3), Comment = rep('', 3))
df2 <- data.frame(Prod = '1.C.1612', Num = '1', Comment = 'my cor.')
df1[] <- df2
df1
#> Prod Num Comment
#> 1 1.C.1612 1 my cor.
#> 2 1.C.1612 1 my cor.
#> 3 1.C.1612 1 my cor.
创建于2023-06-12,使用 reprex v2.0.2
英文:
It's simply
df1[] <- df2
Here's a full reprex as a demo:
df1 <- data.frame(Prod = c('1.C.232', '1.C.231', '1.C.433'),
Num = rep('', 3), Comment = rep('', 3))
df2 <- data.frame(Prod = '1.C.1612', Num = '1', Comment = 'my cor.')
df1[] <- df2
df1
#> Prod Num Comment
#> 1 1.C.1612 1 my cor.
#> 2 1.C.1612 1 my cor.
#> 3 1.C.1612 1 my cor.
<sup>Created on 2023-06-12 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论