如何在R中用特定行替换所有选定的df行。

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

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(&quot;PROD&quot;, &quot;Num&quot;, &quot;Comment&quot;)] &lt;- df2[, c(&quot;PROD&quot;, &quot;Num&quot;, &quot;Comment&quot;)]

答案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[] &lt;- df2

Here's a full reprex as a demo:

df1 &lt;- data.frame(Prod = c(&#39;1.C.232&#39;, &#39;1.C.231&#39;, &#39;1.C.433&#39;), 
                  Num = rep(&#39;&#39;, 3), Comment = rep(&#39;&#39;, 3))

df2 &lt;- data.frame(Prod = &#39;1.C.1612&#39;, Num = &#39;1&#39;, Comment = &#39;my cor.&#39;)

df1[] &lt;- df2

df1
#&gt;       Prod Num Comment
#&gt; 1 1.C.1612   1 my cor.
#&gt; 2 1.C.1612   1 my cor.
#&gt; 3 1.C.1612   1 my cor.

<sup>Created on 2023-06-12 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年6月12日 15:46:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454533.html
匿名

发表评论

匿名网友

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

确定