【发布时间】:2020-10-13 23:33:34
【问题描述】:
我搜索了很多,但找不到答案。我在 R 中工作。我有一个包含两种类型列的数据框 - 数字列和字符列。我正在尝试根据字符列中的分组变量来计算数字变量列的描述性统计信息(我使用 psych 库中的 describeBy 函数执行此操作,在循环之外工作得很好)。此外,我想对原始数据框中的行子集进行相同的分析,因此我创建了另一个子集数据框。 所以,我有两个数据框,每个都有三个字符列和四个数字列。数据框如下所示:
MET.1 CEM.2 CEM.3 par aic od wd
1 healthy healthy healthy 1 6 279 126
2 healthy healthy cem 1 6 244 159
3 met healthy healthy 1 8 222 131
4 met cem healthy 1 4 219 122
5 healthy healthy healthy 1 3 216 129
6 healthy healthy healthy 3 6 204 107
复制:
df <- data.frame(MET.1 = c("healthy", "healthy", "met", "met",
"healthy", "healthy"), CEM.2 = c("healthy", "healthy", "healthy",
"cem", "healthy", "healthy"), CEM.3 = c("healthy", "cem",
"healthy", "healthy", "healthy", "healthy"), par = c(1L, 1L,
1L, 1L, 1L, 3L), aic = c(6L, 6L, 8L, 4L, 3L, 6L), od = c(279L,
244L, 222L, 219L, 216L, 204L), wd = c(126L, 159L, 131L, 122L,
129L, 107L))
我想通过每个数据帧(2 次)中的每个分组列(3 次)为每个数字列(4 次)运行 describeBy 函数 - 在三个嵌套循环中运行 24 次,最后将它们连接到一个数据帧。我想把这些参数中的每一个都变成一个字符向量,然后使用这些向量中的变量将适当的列调用到 describeBy 函数。我尝试过这样的事情:
library("tidyverse")
library("psych")
#create vectors containing numerical columns, charcter columns and different dataframe names
numcol = c("par", "aic", "od", "wd")
charcol = c("MET.1", "CEM.2", "CEM.3")
dataset = c("df","df.subset")
# create vector of output objects for easy use of rbind later...
chunks = c()
#for each dataframe, charcter column and numeric column
for (i in 1:length(dataset)) {
for (j in 1:length(charcol)) {
for (k in 1:length(numcol)) {
#create numeric column name in specific dataframe
param = paste0(dataset[i],"$",numcol[k])
#create character column name in specific dataframe
group = paste0(dataset[i],"$",charcol[j])
# try to apply function by using above created column names - DOESN'T WORK
paste0(numcol[k],charcol[j],dataset[i]) = do.call(rbind, describeBy(param, group = group))
#add resulting dataframe name to vector for use in rbind at the end of the loop
chunks = c(chunks,paste0(numcol[k],charcol[j],dataset[i]))
}
}
}
out.df = rbind(chunks)
不起作用。我收到以下错误:
Calling var(x) on a factor x is defunct.
Use something like 'all(duplicated(x)[-1L])' to test for a constant vector.
我手动检查了循环中的每个步骤,问题在于使用我创建的变量将特定数据帧中的特定列名调用到函数。我试图做的是表示列名,即 DataFrame$Column。还尝试了一些带有方括号的版本,例如dataset[i][,numcol[k]] 无济于事。如果有人知道如何解决此问题或有解决方法,请告诉我。
干杯,
罗恩
【问题讨论】: