1

?Following is the R's interactive envirment's output.

I try to change the colnames of P300.H1,P300.GM and Suz12.H1, but didn't work.

> lapply(list(P300.H1,P300.GM,Suz12.H1), function(x) {colnames(x) <- c("chrom","start", "end", "name", "score")})
[[1]]
[1] "chrom" "start" "end"   "name"  "score"

[[2]]
[1] "chrom" "start" "end"   "name"  "score"

[[3]]
[1] "chrom" "start" "end"   "name"  "score"

> colnames(P300.H1)
[1] "V1" "V2" "V3" "V4" "V5"

I think the problem may be about the assignment, but I'm still confused about that.

Can anybody explain to me the reason about that?

Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • check this related, simple answer using setNames http://stackoverflow.com/questions/19942762/assign-column-names-to-list-of-dataframes – ano Oct 15 '15 at 18:34

4 Answers4

2

There may be a better way, and using assign like this can get you into trouble:

d1 <- d2 <- data.frame(x=1, y=2)

myfun <- function(x) {
  x.df <- get(x)
  colnames(x.df) <- c('n1', 'n2')
  assign(x, x.df, env=.GlobalEnv)
}

lapply(c('d1', 'd2'), myfun)
Justin
  • 42,475
  • 9
  • 93
  • 111
1

If you are really changing the column names of each to the identical set of names, here's a sort of trivial way (that's only appropriate for a small number of data frames):

colnames(P300.H1) <- colnames(P300.GM) <- colnames(Suz12.H1) <- c("chrom","start", "end", "name", "score")
joran
  • 169,992
  • 32
  • 429
  • 468
0

Using a for loop here may prove easier and/or safer than using lapply (or atleast that's what came to mind at 4PM on a Friday):

DF <- data.frame(x = c(1, 2, 3,NA), y = c(1,0, 10, NA), z=c(43,NA, 33, NA))
#make your list
yourList <- list(DF,DF)

for (i in seq(yourList)){
  colnames(yourList[[i]]) <- c("foo", "bar", "baz")
}
#Confirm output is right
> lapply(yourList, colnames)
[[1]]
[1] "foo" "bar" "baz"

[[2]]
[1] "foo" "bar" "baz"
Chase
  • 67,710
  • 18
  • 144
  • 161
-1

R passes by value, not by reference, so changing the column names of a data frame within a function won't change it outside the function.

As a simple, reproducible example:

m <- matrix(rnorm(12), ncol=3)
colnames(m) <- c("A", "B", "C")

change.names = function(x) {
    colnames(x) <- c("X", "Y", "Z")
}

change.names(m)
print(colnames(m))

The column names will still be A, B, C. The x within that function is not the matrix m: it is just a copy of it, and any changes you make to it won't apply to the original.

David Robinson
  • 77,383
  • 16
  • 167
  • 187