2

I am using dplyr and have a dataframe where one of the columns contains vectors/lists. I'd like to create a column that contain the element of the vector with index i (an exterior variable).

e.g. with i = 2

link to data

I have tried:

data <- data %>% mutate (element = list_x [i])

But I get the ith element of the column list_x rather than the ith element of each vector contained in the column...

vl237611
  • 51
  • 3

1 Answers1

2

You can use sapply to apply the [ function to each element at position i like this:

data <- data %>%
  mutate(element = sapply(list_x, "[", i))
Simon Larsen
  • 712
  • 3
  • 9
  • Thank you. To complete your answer to reuse your index i, if we compute for example the max. datas of the screenshot : `data=data.frame( list_clusters = I(list(c(0,53),c(0,45,49),c(0,4,11,15,28,110),c(0,4,11,15,28,110),c(0,50,51,81,155))), current_cluster=c(53,45,4,4,50) )`. `targetdata=data %>% mutate (element=sapply(data$list_clusters,"["),maxL=(sapply(list_clusters,'length')))%>% dplyr::rowwise() %>% mutate (element_max=element[maxL])`. – phili_b Oct 04 '19 at 08:38
  • Links for my comment for 1st `dplyr::rowwise()` and `apply()` (and 2nd the tweak for `I()`)[Apply a function to every row of a matrix or a data frame](https://stackoverflow.com/a/44246072/10489) and [Populating data frame cells with more than one value,by markheckmann, July 18, 2016](https://www.r-bloggers.com/populating-data-frame-cells-with-more-than-one-value/) and the asked anwser with index i: `i=5;targetdata=data %>% mutate (element=sapply(data$list_clusters,"["),maxL=(sapply(list_clusters,'length')))%>% dplyr::rowwise() %>% mutate (element_max=element[maxL],element_i=element[i])`. – phili_b Oct 04 '19 at 08:54
  • `data$` have to be removed in my example. `i=5;targetdata=data %>% mutate (element=sapply(list_clusters,"["),maxL=(sapply(list_clusters,'length')))%>% dplyr::rowwise() %>% mutate (element_max=element[maxL],element_i=element[i])` – phili_b Oct 21 '19 at 11:44