transfer of the value of one parameter to the previous line

There is a task: to sort through all the rows in the data table, and if the value in a certain column is greater than zero, and in the previous row it is equal to zero or NA, then assign this value to the previous row, and delete this row from the table. Sample code, but not working:

for(row in 1:nrow(merged))
{
if (merged$Ант.ок.пр[row] > 0 & is.null(merged$Ант.ок.пр[row-1]) | is.na(merged$Ант.ок.пр[row-1]))
{
merged$Ант.ок.пр[row-1] <- merged$Ант.ок.пр[row]
merged <- merged[-row, ]
}
}

I personally would use dplyr's lag function for a question like this.

For example,

library(dplyr)
df <- data.frame(year = 2000:2005, value = (0:5) ^ 2)
scrambled <- df[sample(nrow(df)), ]

scrambled %>%  
  mutate(
    prev = lag(value, order_by = year)) %>% 
  arrange(year)
#>   year value prev
#> 1 2000     0   NA
#> 2 2001     1    0
#> 3 2002     4    1
#> 4 2003     9    4
#> 5 2004    16    9
#> 6 2005    25   16

Created on 2019-11-07 by the reprex package (v0.3.0)

Full details here:

In your example, it turns out, a new table "scrambled" is created, but this new column "prev" itself (at least visually) is missing. How can I add it?

If you want the column prev to be added to the data frame (rather than just printed to the console), you just need to assign the data frame to an object:

new_scrambled <-
scrambled %>%  
  mutate(
    prev = lag(value, order_by = year)) %>% 
  arrange(year)

new_scrambled

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.