Peng Peng
Peng Peng

Reputation: 1365

What is the difference between colnames(x[1])<-"name" and colnames(x)[1]<-"name"?

I want to rename column names in data.frame,

> x=data.frame(name=c("n1","n2"),sex=c("F","M"))
> colnames(x[1])="Name"
> x
  name sex
1   n1   F
2   n2   M
> colnames(x)[1]="Name"
> x
  Name sex
1   n1   F
2   n2   M
> 

Why does colnames(x[1]) = "Name" not work, while colnames(x)[1]="Name" does?

What is the reason? What is the difference betweent them?

Upvotes: 3

Views: 508

Answers (2)

Charles
Charles

Reputation: 4469

The too much information answer: If you look at what each of the options "de-sugars" to:

# 1.
`[<-`(x, 1, value=`colnames<-`(x[1], 'Name'))
# 2.
`colnames<-`(x, `[<-`(colnames(x), 1, 'Name'))

The first option makes a new data.frame from just the first column, renames that column (successfully), and then tries to assign that data.frame back over the first column. [<-.data.frame will propagate the values, however will not rename existing columns based on the names of value.

The second option gets the colnames of the data.frame, updates the first value, and creates a new data.frame with the updated names.


(Answer to @Peng Peng's question here because I can't figure out how to get backtick quoting to work in a comment...)

The backtick is to quote the variable name. Consider the difference here:

x<-1
`x<-`<-1

The first assigns 1 to a variable called x, but the second assigns to a variable called x<-. These unusal variable names are actually used by the <- primitive function - you are allowed arbitrary function calls on the lhs of an assignment, and a function with <- appended to the name specifies how to perform the update (similar to setf in lisp).

Upvotes: 5

Dirk is no longer here
Dirk is no longer here

Reputation: 368251

Because you want to modify the column names attribute of x, a data.frame. Hence

colnames(x) <- ....

is correct, whether or not you assign one or more at the same time.

Upvotes: 1

Related Questions