如何在 R 中重组数据框?
How to restructure a dataframe in R?
我有一个通过一系列插入数值数组的函数生成的数据框。 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() 这样的函数?
您的某些列似乎本身就是数据框,您需要将它们转回向量,这是您的操作方法
## 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)
我有一个通过一系列插入数值数组的函数生成的数据框。 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() 这样的函数?
您的某些列似乎本身就是数据框,您需要将它们转回向量,这是您的操作方法
## 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)