Home > database >  extracting from the list with condition in R
extracting from the list with condition in R

Time:07-08

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?

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

CodePudding user response:

Maybe

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

CodePudding user response:

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)

CodePudding user response:

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

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