Home > database >  How to obtain a logical (T/F) result when I reach the last row of data in r?
How to obtain a logical (T/F) result when I reach the last row of data in r?

Time:04-30

I am looking to obtain a vector of T/F values based on whether I have reached the last row of data or not. I have attached an example data frame below.

df <- structure(list(A = 1:24, B = 2:25), class = "data.frame", row.names = c(NA, -24L))

Here is my desired output given the provided data.

c("F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", 
  "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "F", "T")

Would be great if this was a function similar to is.na such that I could include in an ifelse statement.

i.e.,

df$new_variable <- ifelse(if.last(df) == 'T' & df$B == 25, 0, df$B)

CodePudding user response:

You can try this:

1:nrow(df) == nrow(df)

To make it a function:

is.last <- function(data) {
  1:nrow(data) == nrow(data)
}

is.last(df)
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE

CodePudding user response:

It is easier with rep

df$new_variable <- rep(c(FALSE, TRUE), c(nrow(df)-1, 1))

Or create a column of FALSE and assign back the last row to TRUE

df$new_variable <- FALSE
df$new_variable[nrow(df)] <- TRUE

Or if we need a matrix

row(df) == nrow(df)

Or for a single column

seq_along(df[[1]]) == nrow(df)

CodePudding user response:

Created a little function for myself that solves this simple example.

if.last <- function(x) ifelse(row(x) < nrow(x), 'F', 'T')
if.last(df)
      [,1] [,2]
 [1,] "F"  "F" 
 [2,] "F"  "F" 
 [3,] "F"  "F" 
 [4,] "F"  "F" 
 [5,] "F"  "F" 
 [6,] "F"  "F" 
 [7,] "F"  "F" 
 [8,] "F"  "F" 
 [9,] "F"  "F" 
[10,] "F"  "F" 
[11,] "F"  "F" 
[12,] "F"  "F" 
[13,] "F"  "F" 
[14,] "F"  "F" 
[15,] "F"  "F" 
[16,] "F"  "F" 
[17,] "F"  "F" 
[18,] "F"  "F" 
[19,] "F"  "F" 
[20,] "F"  "F" 
[21,] "F"  "F" 
[22,] "F"  "F" 
[23,] "F"  "F" 
[24,] "T"  "T" 
df$new_variable <- ifelse(if.last(df) == 'T', 0, df$B)
tail(df)
    A  B new_variable 
19 19 20             20 
20 20 21             21 
21 21 22             22 
22 22 23             23 
23 23 24             24 
24 24 25              0 
  • Related