working with list in r

Hi, I have a column with true false in a list.

TF_col

c(TRUE, TRUE, FALSE, FALSE, TRUE…..FALSE)

c(TRUE, FALSE, FALSE, FALSE, TRUE…..TRUE)

c(TRUE, TRUE, TRUE, TRUE, TRUE…..TRUE)

All lists in this column are length 22. Each element in this list describes whether a given column in the dataset matches a criteria that results in either TRUE OR FALSE.

My goal is to see the percent in which each element in this list is TRUE. For example, for each element that appears first in the list, what is the percent in which it appears TRUE? Is there a quick way for me to do this and output a tiny dataset of this?preferably using tidy verse. thanks u

You mean something like this :

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
set.seed(2022)
df1 <- data.frame(
  id = letters[1:4]
)
df2 <- df1 |>
  rowwise() |>
  mutate(
  f1 = list(sample(c(TRUE,FALSE),22,replace=T)),
  p1 = sum(f1) / length(f1)
  ) 
print(df2)
#> # A tibble: 4 × 3
#> # Rowwise: 
#>   id    f1            p1
#>   <chr> <list>     <dbl>
#> 1 a     <lgl [22]> 0.5  
#> 2 b     <lgl [22]> 0.455
#> 3 c     <lgl [22]> 0.545
#> 4 d     <lgl [22]> 0.455
Created on 2022-08-23 by the reprex package (v2.0.1)

I understood the request to be calculating the fraction of TRUE values in the ith value of each row. That is, using @HanOostdijk's example, of the four first elements in p1, what fraction are TRUE. You would get 22 values. Here is my version of doing that.

library(purrr)
library(tibble)
#> Warning: package 'tibble' was built under R version 4.1.2
DF <- tibble(OtherThing = 1:4, 
             T_F = list(c(TRUE, FALSE, TRUE),
                        c(FALSE, FALSE, TRUE),
                        c(TRUE, TRUE, TRUE),
                        c(FALSE, FALSE, FALSE)))


pmap_int(DF$T_F, sum)/nrow(DF)
#> [1] 0.50 0.25 0.75

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

1 Like

ah yes. thank u <3 so much

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.