FOR循环在R中运行 [英] for loop to function in R
本文介绍了FOR循环在R中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将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
推荐答案
建议:
- 注意在正确的位置返回,在Each for循环的末尾返回永远不会正确
- 尝试了解您正在增长的对象,
res
在您的循环中每次都会被新值擦除,在测试前一步之前不要编程下一步 - 不需要时不要相互转换数字、字符、逻辑索引
- 如果可以循环名称,则不要循环数字索引;如果可以直接循环项,则不要循环名称。
- 尽可能使用
lapply
而不是for
循环 - 在您的函数中使用
browser()
以了解您在做什么。 - 如果可能,请将数据参数放在第一位(我在下面这样做并不是为了重现您请求的输出)
- 玩得开心:)
我认为您需要以下内容
my.function <- function(var, df){
df <- Filter(is.numeric, df)
lapply(var, function(nm) {
# browser() # uncomment, run and print objects to understand what these steps do
split_data <- split(df, df[[nm]])
cols <- lapply(split_data, function(x) psych::describe(x)["mean"])
df <- do.call(cbind, cols)
names(df) <- paste(nm, names(split_data), sep = ".")
df
})
}
my.function(c("vs", "am"), mtcars)
#> [[1]]
#> vs.0 vs.1
#> mpg 16.6166667 24.557143
#> cyl 7.4444444 4.571429
#> disp 307.1500000 132.457143
#> hp 189.7222222 91.357143
#> drat 3.3922222 3.859286
#> wt 3.6885556 2.611286
#> qsec 16.6938889 19.333571
#> vs 0.0000000 1.000000
#> am 0.3333333 0.500000
#> gear 3.5555556 3.857143
#> carb 3.6111111 1.785714
#>
#> [[2]]
#> am.0 am.1
#> mpg 17.1473684 24.3923077
#> cyl 6.9473684 5.0769231
#> disp 290.3789474 143.5307692
#> hp 160.2631579 126.8461538
#> drat 3.2863158 4.0500000
#> wt 3.7688947 2.4110000
#> qsec 18.1831579 17.3600000
#> vs 0.3684211 0.5384615
#> am 0.0000000 1.0000000
#> gear 3.2105263 4.3846154
#> carb 2.7368421 2.9230769
由reprex package(v2.0.1)在2021-11-22创建
这篇关于FOR循环在R中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文