Extract elements from a colum with lists

Hi! I have two questions. For that, I would like to share my reprex:


set.seed(1234) #win-10 OS
a <- list(runif(100))
b <- list(runif(99))
c <- list(runif(98))
d <- list(runif(97))

Column_Asked <- c(a,b,c,d)

df_reprex <- tibble::tibble(Column_Asked)

pluck(df_reprex$Column_Asked,1)[1] # gives 0.1137

pluck(df_reprex$Column_Asked,2)[1] # gives 0.03545673

What I want to do is - how the reprex shows - to find a way to extract the first element of each list that composes the column "Column_Asked" of "df_reprex". Is there a better way than use pluck for that?

A problem with this approach is that the "df" that I am working, my "Column_Asked" has almost 75k rows. For that, I just create this function - using the df_reprex's number of rows - :

extract_data_reprex <- function(data){
 i <- 0
 b <- c(0)

  for(i in 1:4){
  b[i] <- pluck(df_reprex$Column_Asked,i)[1]
 return(tibble(Data_Requested = b))


However, pluck - in my formula - requires (for the use of pluck) a vector named "df_reprex$Column_Asked". So, is there a better way to subset a dataframe using rlang?. In the same df, there are almost 7 "Column_Asked"

Please, any help will be highly appreciated.

PS If there is something unclear, please let me know.

I'm not sure I understand your requirements.
I'm assuming that your starting point/challenge, is a dataframe which has the structure of df_reprex as you provided it. I.e. that it is a set of rows, each row being an arbitrary list.
You want the first element of each list.
If so, this a simple approach:

df2<- df_reprex %>% rowwise() %>% 
  mutate(first_element = Column_Asked[[1]]) 
> df2
Source: local data frame [4 x 2]
Groups: <by row>

# A tibble: 4 x 2
  Column_Asked first_element
  <list>               <dbl>
1 <dbl [100]>         0.114 
2 <dbl [99]>          0.0355
3 <dbl [98]>          0.639 
4 <dbl [97]>          0.115

Thanks a lot! I didn't think about rowwise at all!
Now, I resolved also the formula using this (maybe could help someone):

extract_data_reprex_2 <- function(data, ...){
 i <- 0
 b <- c(0)
 data_2 <- tibble()
 by <- enquos(...)
 data_2 <- data %>% rowwise() %>% 
  mutate(first_element = (!!!by)[[1]]) 

extract_data_reprex_2(df_reprex, Column_Asked)

Thanks so much!

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