2016-12-23 38 views
1

我想在R.如何將lapply的結果轉換爲R中的矩陣?

lapply使用而且我的函數如下所示:

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

我怎樣才能得到的lapply顯示到我可以使用進一步的計算矩陣中的結果呢?我嘗試了以下內容,但沒有幫助,因爲數字不是數字,我不能使用例如'$'來選擇列。

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

而不是使用'$',你可以使用'[['。請提供一個可重現的小例子和預期輸出。另外,如果「國家」不是numieric,data.frame的輸出會更好,因爲'matrix'只能容納一個類。因此,函數中的Res < - data.frame(Country,Nrow)'並使用'do.call(rbind,lapply(countries_list,func_countires))' – akrun

回答

1

你的方法不一定是最好的方法;正如@akrun所說,數據框似乎比矩陣更合適,像dplyrdata.table這樣的軟件包可以更優雅地執行這些聚合。

但要回答你的問題:你可以使用byrow參數來得到你(可能)想要的。

我創建了一個小向量a,它應該類似於您使用的unlist(lapply(的輸出。

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"