R cannot find function

I am trying to rename a column without creating an object (dataframe).

When I run:

names(data.frame(cbind(LETTERS[1:3],1:3)))[1]<-"A"

I get:

Error in names(data.frame(cbind(LETTERS[1:3], 1:3)))[1] <- "A" : could not find function "data.frame<-"

If I run:

X<-data.frame(cbind(LETTERS[1:3],1:3))
colnames(X)[1]<-"letters"
X

I will see the column name changed because I created a data frame and then changed it. I am sure that these two pieces of code are the same except for creating an object. I do not know if R is simply inflexible in this function, and I sometimes have to create objects, and not others. But the error "... could not find the function" seemed a little strange to me. Can someone explain this error?

+4
source share
2 answers

As others have said, you must first name the data frame. (Although there is a way to avoid this, stay tuned.) But you already knew this and wanted to know why. Here it is.

, , - . " ", . . : fooobar.com/questions/57282/....

, .

names(d) <- c("A","B")
d <- `names<-`(d, c("A","B"))

( cbind out)

tmp <- cbind(LETTERS[1:3],1:3)
data.frame(tmp) <- `names<-`(data.frame(tmp), c("A","B"))

tmp <- `data.frame<-`(tmp, `names<-`(data.frame(tmp), c("A","B")))

, data.frame<-.

, , names<-, , .

`names<-`(data.frame(tmp), c("A","B"))
+15

? :

> (colnames(X)[1]<-"letters")
[1] "letters"

, , . , setNames , :

> setNames(data.frame(cbind(LETTERS[1:3],1:3)), c("letters"))
  letters NA
1       A  1
2       B  2
3       C  3

:

> data.frame(letters=LETTERS[1:3], 1:3)
  letters V2
1       A  1
2       B  2
3       C  3
+5

Source: https://habr.com/ru/post/1529462/


All Articles