2
I have a database that is updated monthly, which has 7 columns: USUÁRIO
, and the last 6 months of the year with the amount of purchases for each month.
Following example:
print(DADOS)
USUÁRIO JAN FEV MAR ABR MAI JUN
001 4 3 2 0 4 7
002 1 9 0 1 1 9
003 0 1 2 3 4 0
004 2 4 0 8 0 6
The difficulty is when I need to select the last 3 months to calculate a sum. Selecting by the column name apparently solves the problem...
DADOS = DADOS %>%
select(ABR,MAI,JUN) %>%
mutate(SOMA = sum(ABR,MAI,JUN))
print(DADOS)
USUÁRIO JAN FEV MAR ABR MAI JUN SOMA
001 4 3 2 0 4 7 20
002 1 9 0 1 1 9 21
003 0 1 2 3 4 0 10
004 2 4 0 8 0 6 20
But the problem starts with the next monthly update, which instead of searching for the last 3 months (MAI,JUN,JUL
), he continues to seek (ABR,MAI,JUN
), it seems obvious that this would go wrong, but the question is how to select the last 3 columns of a data frame that does not search by name but by position?
Thanks for the reply @Marcus Nunes, I will test.
– Izak Mandrak
@Izakmandrak if Marcus Nunes' answer satisfied you please consider it as the solution to your problem.
– Flavio Silva
@Flaviosilva as soon as I test the solution and find out if it satisfies or not, I will accept the answer smoothly, just as I did with my other questions. Thank you for reminding.
– Izak Mandrak
@Marcus Nunes it is possible to use mathematical operations after the use of
tail
? You can select the last 3 columns and then add them?– Izak Mandrak