【发布时间】:2022-01-01 03:23:13
【问题描述】:
我正在尝试将 for 循环转换为函数。预期结果是Summ.Stats。任何帮助将不胜感激,以获得b的函数格式的预期结果(Summ.Stats)。
CN = colnames(mtcars);CN
var <- c("vs", "am")
Summ.Stats <- NULL
library(psych)
for (i in 1:(length(var))) {
temp <- which(CN == var[i])
aux.0 <- mtcars %>% filter(mtcars[,temp]==0)
aux.1 <- mtcars %>% filter(mtcars[,temp]==1)
fname.0 <- paste0(paste(var[i], "0", sep = "_"))
fname.1 <- paste0(paste(var[i], "1", sep = "_"))
Summ.0 <- describe(aux.0)
Summ.1 <- describe(aux.1)
tab <- round(cbind(Summ.0$mean, Summ.1$mean), 4)
rownames(tab) <- colnames(aux.0)
colnames(tab) <- c(fname.0, fname.1)
Summ.Stats [[i]] <- tab
}
Summ.Stats #EXPECTED OUTCOME
我尝试的是以下内容;
Summ.Stats <- NULL
my.function <- function(var, df){
df <- df[, !sapply(df, is.character)]#REMOVE THE CHARACTER COLUMNS
CN = colnames(df)
for (i in 1:length(var)) {
temp <- which(CN == var[i])
#
res <- split(df, df[,temp])
names(res) <- paste(var[i], names(res), sep = ".")
return(res) }
for (j in 1:length(res)){
tab <- describe(res[[j]]) #here the mean of res[[1]] and res[[2]] should be saved
Summ.Stats [[j]] <- tab
return(Summ.Stats)
}
}
b <- my.function(var, mtcars);b #only shows vs.0 and vs.1
【问题讨论】:
-
将您的 return 语句移出您的
for循环。在 mkoment,您在第一个for循环的第一次迭代期间从my.function返回。
标签: r function for-loop data-manipulation