1

I have a list of dataframes x with column V1 that says the country and V2 that says the year.

The names of the dataframes are y1, y2, y3 and so on. I want to rename them so that they show the country and year (ALBANIA1993, JAPAN2002, etc.). The following code works individually on the dataframes:

y1 <- as.data.frame(cbind(c("ALBANIA", "ALBANIA", "ALBANIA"), c(1999, 1999, 1999)))
y2 <- as.data.frame(cbind(c("JAPAN", "JAPAN", "JAPAN"), c(2002, 2002, 2002)))
x <- list(y1, y2)

assign(as.character(with(y1, paste0(y1$V1[1], y1$V2[1]))), y1)
assign(as.character(with(y2, paste0(y2$V1[1], y2$V2[1]))), y2)

I am trying to use lapply to apply this to all dataframes from list x at once.

Here's the code:

x <- list(y1, y2)
x <- lapply(x, function(y) assign(as.character(with(y, paste0(y$V1[1], y$V2[1]))), y))

As you can see, it is the same code as before, but inside lapply. For some reason, the dataframes in x don't get renamed and there's no error shown.

Really appreciate the help! I'll edit in case you want more info.

A. Suliman
  • 12,923
  • 5
  • 24
  • 37
Marco Pastor Mayo
  • 803
  • 11
  • 25
  • 1
    Please make this question *reproducible*. This includes sample data (e.g., `dput(head(x))`), and expected output. Refs: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans Sep 22 '18 at 17:28

2 Answers2

2

Instead of using assign you could just reassign the names with names:

x1 <- as.data.frame(cbind(c("ALBANIA", "ALBANIA", "ALBANIA"), c(1999, 1999, 1999)))

x2 <- as.data.frame(cbind(c("JAPAN", "JAPAN", "JAPAN"), c(2002, 2002, 2002)))
x <- list(x1, x2)

theRenamer = function(input.list, ...){
  newNames = lapply(input.list,function(y) as.character(with(y, paste0(y[1,1], y[1,2])))) # get the names you want to assign
  names(input.list) = as.character(newNames) # assign them with "names"
  return(input.list) # return the list
}
x = theRenamer(x)

The function could likely be simplified.

EDIT:

Yup, here's a one-liner:

names(x) = as.character(lapply(
    x,function(y) as.character(with(y, paste0(y[1,1], y[1,2])))))
desc
  • 1,190
  • 1
  • 12
  • 26
2

Using setNames

x <- lapply(x, function(x) setNames(x,nm=c(as.character(x$V1[1]),as.character(x$V2[1]))))

If you read y1 using stringsAsFactor=FALSE then you can remove as.character

A. Suliman
  • 12,923
  • 5
  • 24
  • 37