r - R ; How can I build 'for in' loops over datatable?
问题描述
How can I play loop over datatables?
I have 6 datatable named 'tax2015' 'tax2016' 'tax2017'...'tax2020'.
They have the same header [month, tax, average].
And I'm trying to change the third name of each header, 'average' to 'sum'.
Let's imagine there's 6 datatables named like above, each of them 12 by 3.
for (x in tax2015) {
names(x)[3] <- paste("sum")
}
I made code like this and it doesn't work. Don't know why..
F <- function(a){
if(1>0){
for (x in a)
names(x)[3] <- paste("sum")
}
return(x)
}
F(tax2015)
Tried this too, but doesn't work.
Add to this, how can I do this work for 6 serial data.tables 'tax2015' 'tax2016' 'tax2017'...'tax2020' at one time?
like..
for(x in tax2015:tax2020) {
names(x)[3] <- paste("sum")
}
This doesn't work, is there some ways to do this?
解决方案
手动或使用mget
特定模式将它们放入列表中
list_df <- mget(ls(pattern = "tax\\d+"))
#list_df <- list(tax2015, tax2016, tax2017, ...)
然后用于lapply
在特定位置更改名称
list_df <- lapply(list_df, function(x) {names(x)[3] <- "sum";x})
您可以将数据框保存在列表中或将它们放在单独的数据框中
list2env(list_df, .GlobalEnv)
考虑这个例子,
tax2015 <- data.frame(month = 1:5, tax = 6:10, average = 11:15)
tax2016 <- data.frame(month = 1:5, tax = 6:10, average = 11:15)
tax2017 <- data.frame(month = 1:5, tax = 6:10, average = 11:15)
list_df <- mget(ls(pattern = "tax\\d+"))
list_df <- lapply(list_df, function(x) {names(x)[3] <- "sum";x})
list_df
#$tax2015
# month tax sum
#1 1 6 11
#2 2 7 12
#3 3 8 13
#4 4 9 14
#5 5 10 15
#$tax2016
# month tax sum
#1 1 6 11
#2 2 7 12
#3 3 8 13
#4 4 9 14
#5 5 10 15
#$tax2017
# month tax sum
#1 1 6 11
#2 2 7 12
#3 3 8 13
#4 4 9 14
#5 5 10 15
推荐阅读
- javascript - 简单代码Rails上的JQuery无效或意外令牌
- c# - C# - 如何将 html 输入值传递给 url.Action
- visual-studio - 在 Visual Studio Community 7 中,如何阻止 Tab 创建空间?
- bash - 如何将 HDFS 小文件合并为一个大文件?
- azure - Azure 搜索服务与最新 Azure SQL 数据库实例中的全文搜索?
- google-apps-script - 谷歌脚本从谷歌趋势中导入数据
- python - python中带有scrapy和mongodb的异步HTTP服务器
- kubernetes - 无法引导(云类型:localhost)- 使用 LXD/Conjure-up 在本地安装 Kubernetes 集群时出错
- java - 按照文件中定义的顺序获取所有 JSON 密钥
- azure - 技术堆栈问题:聊天机器人到数据库以显示分析和图表