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


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)

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 ( 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')))


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