Subtracting two specific rows in multiple columns and the result as a new row.

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

subtracting two specifics row in multiple columns and the result as a new row

问题

以下是您要求的代码部分的翻译:

  1. # 假设我有以下数据框:
  2. df <- data.frame("index" = c(1, 2, 3, 4, 5, "total"), "age" = c(10, 20, 30, 40, "non", 18), "1" = c(1, 4, 5, 6, 7, 9), "2" = c(8, 9, 5, 6, 11, 13))
  3. # 我想从第五行减去第六行的X1和X2列,然后将结果作为新行添加。我的预期输出应该是这样的:
  4. # (接下来是您提供的输出示例)
  5. # 我尝试了以下代码但遇到了错误:
  6. num_cols <- ncol(df)
  7. df_result <- data.frame()
  8. for (col in 1:num_cols) {
  9. if (col == 1 || col == 2) {
  10. df_result[, col] <- df[, col]
  11. } else {
  12. new_row <- df[5, ]
  13. new_row[col] <- df[5, col] - df[6, col]
  14. df_result <- rbind(df_result, new_row)
  15. }
  16. }

希望这有助于您理解代码部分的翻译。如果您需要进一步的帮助,请随时提出。

英文:

suppose I have following data frame:

  1. df &lt;- data.frame(&quot;index&quot; = c(1,2,3,4,5,&quot;total&quot;),&quot;age&quot;=c (10,20,30,40,&quot;non&quot;,18) ,&quot;1&quot;=c(1,4,5,6,7,9),&quot;2&quot;=c(8,9,5,6,11,13))

I want to subtract row 6 from row 5 in columnX1 and X2 and then add the result as a new row. my expected output whold be like this:

  1. index age X1 X2
  2. 1 10 1 8
  3. 2 20 4 9
  4. 3 30 5 5
  5. 4 40 6 6
  6. 5 non 7 11
  7. total 18 9 13
  8. 0 0 2 2

I tried following codes but got erros:

  1. num_cols &lt;- ncol(df)
  2. df_result &lt;- data.frame()
  3. for (col in 1:num_cols) {
  4. if (col == 1 || col == 2) {
  5. df_result[, col] &lt;- df[, col]
  6. } else {
  7. row
  8. new_row &lt;- df[5, ]
  9. new_row[col] &lt;- df[5, col] - df[6, col]
  10. df_result &lt;- rbind(df_result, new_row)
  11. }
  12. }

答案1

得分: 2

你可以使用[来通过赋值创建新的行。df[x, 3:4]选择第x行和第3列到第4列。-是向量化的,所以不需要使用for循环。使用&lt;-可以将新值赋给新的行。空列将被填充为NA

  1. df[7, 3:4] &lt;- df[6, 3:4] - df[5, 3:4]
  2. # index age X1 X2
  3. # 1 1 10 1 8
  4. # 2 2 20 4 9
  5. # 3 3 30 5 5
  6. # 4 4 40 6 6
  7. # 5 5 non 7 11
  8. # 6 total 18 9 13
  9. # 7 &lt;NA&gt; &lt;NA&gt; 2 2
英文:

You can create a new row by assignment with [. df[x, 3:4] select the xth row and the 3rd and 4th column. - is vectorized, so not for a for loop. With &lt;- you can assign the new values to a new row. Empty columns are filled with NAs.

  1. df[7, 3:4] &lt;- df[6, 3:4] - df[5, 3:4]
  2. # index age X1 X2
  3. # 1 1 10 1 8
  4. # 2 2 20 4 9
  5. # 3 3 30 5 5
  6. # 4 4 40 6 6
  7. # 5 5 non 7 11
  8. # 6 total 18 9 13
  9. # 7 &lt;NA&gt; &lt;NA&gt; 2 2

huangapple
  • 本文由 发表于 2023年8月4日 20:36:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76835968.html
匿名

发表评论

匿名网友

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

确定