Apollo
Apollo

Reputation: 9064

Simple table in R

How would I create a simple table in R with two columns and 5 rows? I currently have the following loop:

for (i in 0:5) {
  red <- sprintf("%d white balls and not the red ball: %f",i,win_balls(i, TRUE))
  not_red <- sprintf("%d white balls and the red ball: %f",i,win_balls(i, FALSE))
  print(not_red)
  print(red)
}

Instead of printing not_red and red I'd like to store them each in a respective column in a table. So the table would like like this:

Not Red  Red
0        2
1        3
4        5

Upvotes: 0

Views: 346

Answers (1)

Molx
Molx

Reputation: 6931

You can use lapply to create that as a matrix:

do.call(rbind, lapply(0:5, function(i) {
  c(i, i*2)
}))

Or t(sapply()):

t(sapply(0:5, function(i) {
  c(i, i*2)
}))

Then you just have to set the column names.

For your win_balls function, probably this would work

balls <- do.call(rbind, lapply(0:5, function(i) {
  c(win_balls(i, TRUE), win_balls(i, FALSE))
}))
colnames(balls) <- c("NotRed", "Red")

Upvotes: 1

Related Questions