1

我有一个通过一系列插入数值数组的函数生成的数据框。df 由 156 个变量组成,每个变量有 4261 个观测值。我试图找到每列的平均值,但 colMeans() 函数给出以下错误:

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

我认为我使用的功能之一是创建数据帧并将其附加到现有的 df,因此数组结构中的“data.frame”。

有没有一种方法可以将数据帧重组为可以运行 colMeans() 和 colSums() 等函数的数据帧?

4

1 回答 1

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)
于 2017-06-01T14:25:19.653 回答