user3575876
user3575876

Reputation: 355

Assign names to list elements without titled quotes

I am interested to assign names to list elements. To do so I execute the following code:

file_names <- gsub("\\..*", "", doc_csv_names)
print(file_names)
"201409" "201412" "201504" "201507" "201510" "201511" "201604" "201707"
names(docs_data) <- file_names

In this case the name of the list element appears with ``.

docs_data$`201409`
However, in this case the name of the list element appears in the following way:
names(docs_data) <-  paste("name", 1:8, sep = "")
docs_data$name1

Upvotes: 2

Views: 465

Answers (1)

doubled
doubled

Reputation: 349

Both gsub and paste return character objects. They are different because they are completely different functions, which you seem to know based on their usage (gsub replaces instances of your pattern with a desired output in a string of characters, while paste just... pastes).

As for why you get the quotations, that has nothing to do with gsub and everything to do with the fact that you are naming variables/columns with numbers. Indeed, try

names(docs_data) <- paste(1:8)

and you'll realize you have the same problem when invoking the naming pattern. It basically has to do with the fact that R doesn't want to be confused about whether a number is really a number or a variable because that would be chaos (how can 1 refer to a variable and also the number 1?), so what it does in such cases is change a number 1 into the character "1", which can be given names. For example, note that

> 1 <- 3
Error in 1 <- 3 : invalid (do_set) left-hand side to assignment
> "1" <- 3 #no problem!

So R is basically correcting that for you! This is not a problem when you name something using characters. Finally, an easy fix: just add a character in front of the numbers of your naming pattern, and you'll be able to invoke them without the quotations. For example:

file_names <- paste("file_",gsub("\\..*", "", doc_csv_names),sep="")

Should do the trick (or just change the "file_" into whatever you want as long as it's not empty, cause then you just have numbers left and the same problem)!

Upvotes: 2

Related Questions