kanpu
kanpu

Reputation: 261

How to format a dataframe in rmarkdown

I tried to use rmarkdown in rstudio. The problem is that I have a dataframe one col of which is a long string. When I use rmarkdown as the following:

```{r, echo=FALSE}
x1 <- c(1,2)
x2 <- c("aaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbb")
x3 <- c("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxx, xxxxxxxxxxxxxxxxxxx",
       "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy yyyy, yyyyyyyyyyyyyyyyyyyyyy")

df <- data.frame(x1=x1, x2=x2,x3=x3)
```

```{r, echo=FALSE}
df
```

and I get the following output(I use html):

##   x1                  x2
## 1  1      aaaaaaaaaaaaaa
## 2  2 bbbbbbbbbbbbbbbbbbb
##                                                                  x3
## 1    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxx, xxxxxxxxxxxxxxxxxxx
## 2 yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy yyyy, yyyyyyyyyyyyyyyyyyyyyy

First, I don't like to print x3 as a seperate line; second, I prefer left alignment. How can I do that?

Thank you.

Upvotes: 3

Views: 4233

Answers (1)

jbaums
jbaums

Reputation: 27388

You can control the width of the element with options(width=x), and left align by calling print(df, right=FALSE). You can hide this cruft (though you may not want to) with, for example:

---
title: "Interesting data.frame"
author: "Me"
date: "15 April 2015"
output: html_document
---

```{r, echo=FALSE}
options(width=100)
```


```{r}
x1 <- c(1,2)
x2 <- c("aaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbb")
x3 <- c("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxx, xxxxxxxxxxxxxxxxxxx",
        "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy yyyy, yyyyyyyyyyyyyyyyyyyyyy")

df <- data.frame(x1=x1, x2=x2,x3=x3)
```

```{r, eval=FALSE}
df
```

```{r, echo=FALSE}
print(df, right=FALSE)
```

... which yields ...


enter image description here

Upvotes: 5

Related Questions