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

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

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

问题

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

# 假设我有以下数据框:
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))

# 我想从第五行减去第六行的X1和X2列,然后将结果作为新行添加。我的预期输出应该是这样的:
# (接下来是您提供的输出示例)

# 我尝试了以下代码但遇到了错误:
num_cols <- ncol(df)
df_result <- data.frame()
for (col in 1:num_cols) {
  if (col == 1 || col == 2) {
    df_result[, col] <- df[, col]
  } else {
    new_row <- df[5, ]
    new_row[col] <- df[5, col] - df[6, col]
    df_result <- rbind(df_result, new_row)
  }
}

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

英文:

suppose I have following data frame:

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:

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

I tried following codes but got erros:

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

答案1

得分: 2

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

df[7, 3:4] &lt;- df[6, 3:4] - df[5, 3:4]

#   index  age X1 X2
# 1     1   10  1  8
# 2     2   20  4  9
# 3     3   30  5  5
# 4     4   40  6  6
# 5     5  non  7 11
# 6 total   18  9 13
# 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.

df[7, 3:4] &lt;- df[6, 3:4] - df[5, 3:4]

#   index  age X1 X2
# 1     1   10  1  8
# 2     2   20  4  9
# 3     3   30  5  5
# 4     4   40  6  6
# 5     5  non  7 11
# 6 total   18  9 13
# 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:

确定