Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

Convert names of vector objects into the tags of the list of vectors with R

I have some vectors, like this:

months <- c("january", "february", "march", "october", "december") 
weekdays <- c("Sunday", "Monday", "Tuesday")
seasons <- c("Summer", "Winter", "Fall", "autumn")

And I want to create a list like this

timeWords_list <- list(months,  weekdays, seasons)

Is there any way to tag the objects of the list directly with the names of the vector objects?

The result I want can be achieved like this:

names(timeWords_list) <- c("months",  "weekdays", "seasons")

But, Is there any way to do that directly? Without re-writing these names (in a string vector)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try any of these one-liners. The first one does require that each name be written twice but no character vector of names need be provided and the intent of the code is very clear. The second one only requires that the names be written once. The third one does not require that the names be written out at all but only works if there are no other variables whose names end in s -- if there were such names those variables would be included in the list as well.

No packages are used.

L1 <- list(months = months, weekdays = weekdays, seasons = seasons)

L2 <- mget(c("months", "weekdays", "seasons"))

L3 <- mget(ls(pattern = "s$"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...