首页 > 解决方案 > 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?

标签: r

解决方案


手动或使用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

推荐阅读