简体   繁体   中英

How to change column names while in a loop in R?

for(i in 1:3){
  
  names <- c("n1","n2","n3")
  assign(paste0("mydf",i), data.frame(matrix("", nrow = 3, ncol = 3)))
  
}

I tried the code shown below but it didn't work.

for(i in 1:3){
  
  names <- c("n1","n2","n3")
  assign(paste0("mydf",i), names(data.frame(matrix("", nrow = 3, ncol = 3)))[1:3] <- names)
  
}

What's your solution? Thanks in advance.

This the approach I would take. The following script not only changes the column names, but also creates 3 dataframes in the global environment kind of like your original script.

for (i in 1:3){
  noms <- c("n1","n2","n3") # create the names in order the columns appear in the dataframe
  
  df_ <- data.frame(matrix("", nrow = 3, ncol = 3)) # create the dataframe
  
  df_nom <- paste("mydf", i, sep = "") # create the dataframe name
  
  colnames(df_) <- noms # assign the names to the columns
  
  assign(df_nom, df_) # rename the dataframe
}

1) Normally one puts the data frames in a list but if you really want to them into the current environment then do the following. If you want the global environment then replace the first line with e <-.GlobalEnv or if you want to create a list instead (preferable) then use e <- list() instead.

# define 3 data frames
e <- environment()  # or e <- .GlobalEnv or e <- list()
nms <- paste0("mydf", 1:3)
for(nm in nms) e[[nm]] <- data.frame(matrix("", 3, 3))

# change their column names
for(nm in nms) names(e[[nm]]) <- c("n1", "n2", "n3")

2) Even better if we want lists is:

L <- Map(function(x) data.frame(matrix("", 3, 3)), paste0("mydf", 1:3))
L[] <- lapply(L, `names<-`, c("n1", "n2", "n3"))  # change col names

Converting

Note that we can convert a list L to data frames that are loose in the environment using one of these depending on which environment you want to put the list components into.

list2env(L, environment())
list2env(L, .GlobalEnv)

and we can go the other way using where e is environment() or .GlobalEnv depending on what we need. We can omit the e argument is the data frames are in the current environment.

L <- mget(nms, e)

You can use get to get the data.frame by name , update the names and assign it back.

nNames <- c("n1","n2","n3")
for(i in 1:3) {
  D <- paste0("mydf",i)
  tt <- get(D)
  names(tt) <- nNames
  assign(D, tt)
}
names(mydf1)
#[1] "n1" "n2" "n3"

Alternatively the names could already be set when creating the matrix by using dimnames :

nNames <- c("n1","n2","n3")
for(i in 1:3) {
    assign(paste0("mydf", i),
           data.frame(matrix("", 3, 3, dimnames=list(NULL, nNames))))
}
names(mydf1)
#[1] "n1" "n2" "n3"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM