R语言如何将for循环生成的列表对象按指定名称单独保存到环境
实现拆分数据集为独立对象的代码方案
原代码错误修正
你原有代码中colnames(temp) <- paste0(paste(cont[i])) 逻辑错误,会将子集所有列的列名统一修改为大洲名称,不符合预期,需删除该行。
可直接运行的实现代码
方法1:循环内直接赋值
library(gapminder) cont <- unique(gapminder$continent) for(i in seq_along(cont)) { temp <- gapminder[gapminder$continent == cont[i], ] assign(paste0("gapminder_", cont[i]), temp, envir = .GlobalEnv) }
方法2:先生成命名列表再批量导入(更规范)
library(gapminder) cont <- unique(gapminder$continent) df <- list() for(i in seq_along(cont)) { temp <- gapminder[gapminder$continent == cont[i], ] df[[cont[i]]] <- temp } list2env(setNames(df, paste0("gapminder_", names(df))), envir = .GlobalEnv)
效果验证
运行代码后,在控制台输入head(gapminder_Asia)即可得到预期输出:
> head(gapminder_Asia) # A tibble: 6 × 6 country continent year lifeExp pop gdpPercap <fct> <fct> <int> <dbl> <int> <dbl> 1 Afghanistan Asia 1952 28.8 8425333 779. 2 Afghanistan Asia 1957 30.3 9240934 821. 3 Afghanistan Asia 1962 32.0 10267083 853. 4 Afghanistan Asia 1967 34.0 11537966 836. 5 Afghanistan Asia 1972 36.1 13079460 740. 6 Afghanistan Asia 1977 38.4 14880372 786.
内容的提问来源于stack exchange,提问作者symkly
相关产品推荐
相关产品推荐

