How can I transform results from lapply into a matrix in R?

Question

I want to use lapply in R.

Furthermore my function looks like the following:

func_countries <- function(x){
      Country <- x
      Nrow <- nrow(data[which(data$country == x),])
      Res <- list(Country, Nrow)
      return(Res)}

Overview_countries <- unlist(lapply(countries_list, func_countries))

How can I get the result of lapply displayed into a matrix which I can use for further calculations? I tried the following but it wasn't helpful because numbers are not numeric plus I can't use for example '$' to select columns.

Overview_countries <- matrix(Overview_countries, nrow=2, dimnames=list(c('Country', 'Numb_obs')))
Overview_countries <- t(Overview_countries)

Show source
| function   | R   | matrix   | lapply   2016-12-23 12:12 1 Answers

Answers to How can I transform results from lapply into a matrix in R? ( 1 )

  1. 2016-12-23 13:12

    Your approach is not necessarily the best one here; as @akrun said, a data frame would seem more suitable than a matrix, and packages like dplyrand data.table can perform these aggregations more elegantly.

    But to answer your question: you can use the byrow argument to get what you (probably) want.

    I created a little vector a that should be similar to the output of the unlist(lapply( you use.

    a <- list(list('Belgium',25), list('Holland', 89), list('UK', 784))
    a <- unlist(a)
    
    res <- matrix(a, nrow=3, byrow=TRUE, dimnames=list(NULL, c('Country', 'Numb_obs')))
    

    Output:

         Country   Numb_obs
    [1,] "Belgium" "25" 
    [2,] "Holland" "89" 
    [3,] "UK"      "784"
    

Leave a reply to - How can I transform results from lapply into a matrix in R?

◀ Go back