2017-06-01 77 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答案,并单击复选标记,以表明您满意。 –