2017-06-01 83 views
1

我有一個數據框通過一系列插入數值數組的函數生成。 df由156個變量組成,每個變量有4261個觀察值。我想每列的均值,但colMeans()函數提供了以下錯誤:如何重構R中的數據框?

> colMeans(results) 
Error in if (inherits(X[[j]], "data.frame") && ncol(xj) > 1L) X[[j]] <- as.matrix(X[[j]]) : 
    missing value where TRUE/FALSE needed 

我認爲這是與數據框的結構,因此,我試圖改變它,但是那給了另一個錯誤。

> str(results) 
'data.frame': 4261 obs. of 156 variables: 
$ r5.2.5  : num 0 0 0 0 0 0 0 0 0 0 ... 
$ r10.2.5 :'data.frame': 4261 obs. of 1 variable: 
    ..$ ret: num 0 0 0 0 0 0 0 0 0 0 ... 
$ r20.2.5 :'data.frame': 4261 obs. of 1 variable: 
    ..$ ret: num 0 0 0 0 0 0 0 0 0 0 ... 
$ r30.2.5 :'data.frame': 4261 obs. of 1 variable: 
    ..$ ret: num 0 0 0 0 0 0 0 0 0 0 ... 
.... 

> results <- as.data.frame(as.numeric(results)) 
Error in as.data.frame(as.numeric(results)) : 
    (list) object cannot be coerced to type 'double' 
> results <- data.matrix(results) 
Error in data.matrix(results) : 
    (list) object cannot be coerced to type 'double' 

我想的我使用的功能,一個創建dataframes並附着那些對現有的DF,因此在陣列的結構「data.frame」。

有沒有一種方法可以將數據框重構爲可以運行colMeans()和colSums()等函數的數據框?

+1

你'results'object似乎不是一個矩陣中,第二個值'$ r10.2.5'是一個'data.frame'。我認爲這是問題 – R18

+0

這就是我想的,有沒有辦法將它變成一個單一的數據框?我試圖as.data.frame它,但這並沒有改變任何東西。 –

回答

1

它看起來像你的一些列的是數據幀本身,你需要把它們放回載體,這裏是你如何做到這一點

## get the columns in question 

my_dfs <- sapply(results, function(x) is.data.frame(x)) 

## turn them into vectors 

results[,my_dfs] <- sapply(results[,my_dfs], function(x) unlist(x)) 

### then you can do 

my_means <- sapply(results, mean) 
+1

這是完美的,謝謝! –

+0

我很高興它幫助,請考慮upvoting答案,並單擊複選標記,以表明您滿意。 –