[英]Reorder one data.frame using two columns from another data.frame in R
[英]Operations with two lines in one data.frame for all columns in r
我想在 data.frame 的特定行之间执行操作。
例如,考虑以下data.frame:
structure(list(`2020` = c(1264, 5.23, 25475, 34454, 57011,
3,312), `2019` = c(1.57, 5,115, 24,811, 33,414, 50,883, 3,332
), `2018` = c(1,587, 5,373, 25,391, 33,589, 50,547, 3,952), `2017` = c(1,711,
5,675, 24,674, 33,978, 54,903, 4,288), `2016` = c(1,739, 4,507,
24,199, 35,015, 52,051, 4,419), `2015` = c(1,813, 5,631, 25,488,
35929, 56415, 3859)), row.names = c("3", "4", "5", "6", "7",
"8"), class = "data.frame")
我需要在下面创建一个新行,考虑从第 5 行和第 4 行中减去第 7 行,这样这对所有列都有效,所以它看起来像这样:
structure(list(`2020` = c(1264, 5.23, 25475, 34454, 57011,
3,312, 26,306), `2019` = c(1.57, 5,115, 24,811, 33,414, 50,883,
3,332, 20,957), `2018` = c(1,587, 5,373, 25,391, 33,589, 50,547,
3,952, 25,391), `2017` = c(1,711, 5,675, 24,674, 33,978, 54,903,
4,288, 24,554), `2016` = c(1,739, 4,507, 24,199, 35,015, 52,051,
4,419, 23,345), `2015` = c(1,813, 5,631, 25,488, 35,929, 56,415,
3859, 25296)), row.names = c("3", "4", "5", "6", "7", "8",
"9"), class = "data.frame")
我需要在循环中执行此操作,因此 dplyr 解决方案可能更可取,但欢迎提供任何帮助。
我通过这样做实现了它:
df['9',] <- df['7',] - df['5',] - df['4',]
我在第2020
行第9
列中得到的数字与您的示例中的数字不匹配。
2020 2019 2018 2017 2016 2015
3 1264.00 1.57 1587 1711 1739 1813
4 5.23 5115.00 5373 5675 4507 5631
5 25475.00 24811.00 25391 24674 24199 25488
6 34454.00 3414.00 33589 33978 35015 35929
7 57011.00 50883.00 50547 54903 52051 56415
8 3312.00 3332.00 3952 4288 4419 3859
9 31530.77 20957.00 19783 24554 23345 25296
不要在 R 或任何其他语言的numeric
类型列中放置逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.