-3

I have such a list(list1) each element is a data frame which consist one column.

All columsn names are same "x". I want to change column names as "x1", "x2",....,"xn".

I use below code:

lapply(list1, function(x) setNames(x, "x",paste("x",1:seq_along(list1))))  

However, this code does not work. Why does not this code work? I will be very glad for any help. Thanks a lot.

@ David Arenburg, I edited code as below(10 is the elment number in list1):

lapply(list1, function(z) setNames(z,paste0("x",1:10)))

This code does not give any error but it also does not change the column names.The column names ars still "x".

I edited the as below, however, it doesn't still work.

for(i in 1:10)
{
  list2[[i]]<-setNames(data.frame(list1[[i]])[,1], paste0("x",1:10)[i])
}

I removed seq_along for now. I will work on it after gettin the desired result.

Each element of list1 is a data frame and each data frame has only one column.

oercim
  • 1,808
  • 2
  • 17
  • 34
  • 1
    This is not reproducible, but `1:seq_along(list1)` won't work properly. Try `1:seq_along(mtcars)`. This should be just `seq_along(mtcars)`. But in your case it's not clear how do you use `x` here, as you still passing `list1` into `seq_along`. This doesn't make any sense to me. Also, your `setNames` usage is unclear. It should have 2 inputs- not 3. And probably this should be `paste0`- not `paste` as you probably want your names to be synthetically valid. – David Arenburg Mar 27 '16 at 12:57
  • Are you assigning the result to an object? – Roman Luštrik Mar 27 '16 at 13:32
  • `setNames` doesn't modify in place. You need to assign it somewhere. And as I already mentioned, [this isn't reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). And what happened to `seq_along`? And what do you mean by "*consist one column*"? How many columns are there? – David Arenburg Mar 27 '16 at 13:32

1 Answers1

1

If you want to change the name of each column in multiple data frames that make a list, you should do the following:

# Artificial list with each data frame containing columns with values from 1 to 3

list1 = list(data.frame(x = 1:3), data.frame(x = 1:3), data.frame(x = 1:3),
         data.frame(x = 1:3), data.frame(x = 1:3), data.frame(x = 1:3),
         data.frame(x = 1:3), data.frame(x = 1:3), data.frame(x = 1:3),
         data.frame(x = 1:3))

# Assigning column names of individual data frames

for(i in 1:length(list1)){
  colnames(list1[[i]]) = paste("x",i, sep = "")
}

I created a list with multiple data frames each one of them containing same column x. Because you want to change the names of columns in data frames, assigning multiple values in setNames() to each individual data frame will be of no help. Therefore, you have to paste x with single values (from 1 to length of your list) to the column names of individual data frames.

ragoragino
  • 26
  • 2