英文:
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 <- 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))
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 <- ncol(df)
df_result <- data.frame()
for (col in 1:num_cols) {
if (col == 1 || col == 2) {
df_result[, col] <- df[, col]
} else {
row
new_row <- df[5, ]
new_row[col] <- df[5, col] - df[6, col]
df_result <- rbind(df_result, new_row)
}
}
答案1
得分: 2
你可以使用[
来通过赋值创建新的行。df[x, 3:4]
选择第x
行和第3列到第4列。-
是向量化的,所以不需要使用for
循环。使用<-
可以将新值赋给新的行。空列将被填充为NA
。
df[7, 3:4] <- 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 <NA> <NA> 2 2
英文:
You can create a new row by assignment with [
. df[x, 3:4]
select the x
th row and the 3rd and 4th column. -
is vectorized, so not for a for
loop. With <-
you can assign the new values to a new row. Empty columns are filled with NA
s.
df[7, 3:4] <- 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 <NA> <NA> 2 2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论