简体   繁体   中英

Using the object name i in a for loop as a character

I would like to call on a list of objects in a for loop. Within that for loop I would like to use the name of my list object "i" within another list "n" as a character for a label on one of my graphs.

So, i would like i to be a chracters

I have tried

for(i in n){as.character(bquote(.(i))}

but it returns "i", and i need it to return i So, if my object i is named cat, i want "cat", not "i".

And,

 for(i in n){quote(i)}

But, it converts everything within my list into a character.

Alright, here is an example

cat<-c(1,2,3,4)
dog<-c(5,6,7,8)
walrus<-list(cat=cat,dog=dog)

duck<-c(5,5,5,5,5)
goose<-c(6,6,6)
narwhal<-list(duck=duck, goose=goose)

polarbear<-list(walrus=walrus, narwhal=narwhal)

for(i in polarbear){print(as.character(i))}

I want "walrus" and "narwhal" as my output, but only one at a time.

It isn't obvious what you are trying to do, but your data will probably be easier to work with as a data frame. Convert it using the listless package (not yet on CRAN).

Get listless :

library(devtools)
install_bitbucket("graumannlabtools/listless")

Convert to data frame:

library(listless)
(polarbear_data <- list_to_data.frame(polarbear))
##     names1 names2 values
## 1   walrus    cat      1
## 2   walrus    cat      2
## 3   walrus    cat      3
## 4   walrus    cat      4
## 5   walrus    dog      5
## 6   walrus    dog      6
## 7   walrus    dog      7
## 8   walrus    dog      8
## 9  narwhal   duck      5
## 10 narwhal   duck      5
## 11 narwhal   duck      5
## 12 narwhal   duck      5
## 13 narwhal   duck      5
## 14 narwhal  goose      6
## 15 narwhal  goose      6
## 16 narwhal  goose      6

polarbear_data is in a form that will easily work with other tools, like dplyr or ggplot2 .

library(ggplot2)
ggplot(polarbear_data, aes(interaction(names1, names2), values)) + 
  geom_boxplot()

北极熊箱线图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM