我已经搜索了很多次,都找不到答案。我在R中工作,我有一个包含两种列的数据框架--数字列和字符类型的列。我正在尝试根据字符列中的分组变量来计算数字变量列的描述性统计数据(我使用心理库中的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]],但都没有效果。如果有人知道如何解决这个问题或有变通办法,请让我知道。干杯,罗恩
发布于 2020-10-14 17:57:52
您可以将describeBy函数的输出存储在列表中,您是对的,问题在于您如何访问列名。当列名是使用双括号([[]])的字符值时,不能使用$访问列名。
library(psych)
numcol = c("par", "aic", "od", "wd")
charcol = c("MET.1", "CEM.2", "CEM.3")
dataset = list(df, df.subset)
output_list <- vector('list', length(numcol) * length(charcol) * length(dataset))
x <- 0
for (i in seq_along(dataset)) {
for (j in charcol) {
for (k in numcol) {
x <- x + 1
output_list[[x]] <- describeBy(dataset[[i]][[k]],group = dataset[[i]][[j]])
}
}
}output_list将在一个列表中包含describeBy输出的列表。
https://stackoverflow.com/questions/64344547
复制相似问题