Nuñes
Nuñes

Reputation: 107

Operations with two lines in one data.frame for all columns in r

I would like to perform an operation between specific lines of a data.frame.

For example, considering the following 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")

I need to create a new row below considering subtracting row 7 from rows 5 and 4, so that this is valid for all columns, so it looks like this:

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")

I need to perform this operation inside a loop, so a dplyr solution might be preferable, but any help is welcome.

Upvotes: 0

Views: 43

Answers (1)

OldManSeph
OldManSeph

Reputation: 2719

I achieved it by doing this:

df['9',] <- df['7',] - df['5',] - df['4',]

the number i got in column 2020 row 9 doesn't match what is in your example though.

      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

don't put commas in numeric type columns in R or any other language.

Upvotes: 1

Related Questions