user44796
user44796

Reputation: 1219

print table in R using names from vector

I am trying to create a number of table objects that I can insert into an html page unsing Knit and would like to be able to loop through a vector of names to print the corresponding table.

for example:

TabA = as.table(cbind(c("A","B","C"),c(1,2,3)))
TabB = as.table(cbind(c("D","E","F"),c(1,2,3)))

nams = c("TabA","TabB")

Then in the html using R markdown

Example Table: `r nams[4] `

```{r}
knitr::kable(t(nams[4]),format = "markdown")
```

I know how to assign names on the fly, but not sure how to use the vector as a pointer to the object.

Upvotes: 1

Views: 2778

Answers (5)

Dominic Comtois
Dominic Comtois

Reputation: 10401

Not sure where the html file comes in, but for the names issue, it might be wiser to just use a list (and thus avoid any evaluating of strings):

my.tables <- list(TabA=as.table(cbind(c("A","B","C"),c(1,2,3))),
                  TabB=as.table(cbind(c("D","E","F"),c(1,2,3))))

for(tab.name in names(my.tables))
  print(my.tables[[tab.name]])

# Or if you don't like loops
invisible(lapply(my.tables, print))

#   A B
# A A 1
# B B 2
# C C 3
#   A B
# A D 1
# B E 2
# C F 3

Upvotes: 3

IRTFM
IRTFM

Reputation: 263332

If you just want the side-effect of printing then this succeeds with no loop or clunky eval(parse(.)). The mget function provides implicit looping:

invisible(sapply( mget(nams), print))
  A B
A A 1
B B 2
C C 3
  A B
A D 1
B E 2
C F 3

The invisible is used to suppress the extra values that print returns to sapply. You could also drop the invisible wrapper if you assigned the result to a temp variable.

Upvotes: 0

eipi10
eipi10

Reputation: 93791

You can use get, as in:

tab = get(nams[i]) or print(get(nams[i])).

get("string") returns the object with name equal to "string"

Upvotes: 1

Daniel Robertson
Daniel Robertson

Reputation: 1394

eval(parse(text="some clever text here")) will take a string and evaluate it as an expression. You might try something like the following

for(i in names) {
    print(eval(parse(text = i)))
}

parse: https://stat.ethz.ch/R-manual/R-devel/library/base/html/eval.html

eval: https://stat.ethz.ch/R-manual/R-devel/library/base/html/parse.html

Upvotes: 0

Philippe Chavanne
Philippe Chavanne

Reputation: 344

You should use eval and as.name

TabA = as.table(cbind(c("A","B","C"),c(1,2,3))) 
TabB = as.table(cbind(c("D","E","F"),c(1,2,3)))

nams = c("TabA","TabB")

for (i in 1:length(nams)) {
    print(eval(as.name(nams[i])))
}

Upvotes: -1

Related Questions