extracting from the list with condition in R

Viewed 75

I have a list which contains data frames with three columns and different number of rows. As an example one of them is as the table below. df[[2]]. I want to extract for each of the data frame the row where the column "D" is "TRUE" for the first time. for example, the row number 5 in the table below. How can I extract the information? And how can I extract the first and last element of colunmn A from my list? I tried below:

df$first_element_A = unlist(X = df, FUN = function(p_)
{
 p_[which(p_$A)][1]
}))





df$A = 40.51
df$m = 15
df$D = TRUE

I have reach to this code, but not sure how to fix it:

df$A = sapply(X = df, FUN = function(p_) {which (p$D==TRUE )[1]}

enter image description here

3 Answers

Maybe

lapply(df, function(x){head(x[x$D, ], 1)})

First I created two reproducible dataframes in a list. You could use lapply where you extract in each dataframe from your list where the rows has TRUE in column D. You can use the following code:

df1 <- data.frame(m = c(runif(6, 0, 16)),
                 A = c(runif(6,0,16)),
                 D = c("FALSE", "FALSE", "FALSE", "FALSE", "TRUE", "TRUE"))
df2 <- data.frame(m = c(runif(6, 0, 16)),
                 A = c(runif(6,0,16)),
                 D = c("FALSE", "TRUE", "TRUE", "FALSE", "TRUE", "TRUE"))

my_list <- list(df1, df2)

lapply(my_list, function(x) head(x[x$D == "TRUE",], 1))
#> [[1]]
#>            m        A    D
#> 5 0.09949959 10.60356 TRUE
#> 
#> [[2]]
#>          m        A    D
#> 2 9.154188 8.434005 TRUE

Created on 2022-07-08 by the reprex package (v2.0.1)

Here is how to fix your initial attempt using which()

lapply(df, function(p) p[which(p$D)[1], ])

edit answer to follow up question. I assume you mean how to get the first and last elements of column A in the original list.

df <- list(
  df1 = data.frame(m = 21:26,
                  A = 41:46,
                  D = c(F,F,F,F,T,T)),
  df2 = data.frame(m = 11:14,
                  A = 31:34,
                  D = c(F,T,T,T)))

> df
$df1
   m  A     D
1 21 41 FALSE
2 22 42 FALSE
3 23 43 FALSE
4 24 44 FALSE
5 25 45  TRUE
6 26 46  TRUE

$df2
   m  A     D
1 11 31 FALSE
2 12 32  TRUE
3 13 33  TRUE
4 14 34  TRUE

In the list, first element of column A would be 41, and last element would be 34.

> first_in_A <-  df[[1]][1,"A"]
> first_in_A
[1] 41
> last_in_A <- df[[-1]][nrow(df[[-1]]),"A"]
> last_in_A
[1] 34
Related