In this article, I show you how to create a data.frame from a text submitted in a textarea field with FastRWeb.
Requirements
- FastRWeb installed
- Knowledge of webforms
?read.table- Experience in HTML5
Submit
This example needs two scripts. The first one contains the webform. I wrote a FastRWeb script in order to work in /var/FastRWeb/web.R/. This form could have been a static HTML page. Paste the code below in /var/FastRWeb/web.R/tablesubmit.R.
run <- function() {
out("<!doctype html><html lang='en'><head><title>Submit a Table</title>",
"<meta charset='UTF-8'/></head><body><header><h1>Submit a Table</h1>",
"<p>This is an example showing how to read a text posted in a ",
"<code>textarea</code> and create a data frame from it.</p></header>",
sep = "", eol = "")
out("<form method='post' action='textareatodf' ",
"enctype='multipart/form-data' name='form'>", sep = "", eol = "")
out("<p>Paste the table content in the text area below.</p>")
out("<textarea name='MyTable' rows=15 cols=80></textarea>")
out("<br/><input type='submit' /></form>")
out("</body></html>")
done()
}
Output
To retrieve the the submitted data, read them and create your data.frame, you’ll respectively use the functions parse.multipart(), textConnection() and read.table(). These last two are installed with R base. parse.multipart() is available if you have installed la version 1.1 de FastRWeb.
Paste the text below in /var/FastRWeb/web.R/textareatodf.R.
run <- function(MyTable) {
# HTML
out("<!doctype html><html lang='en'><head><title>Data Frame</title>",
"<meta charset='UTF-8'/></head><body><header><h1><code>textarea</code> ",
"to <code>data.frame</code></h1></header>", sep = "", eol = "")
# Retrieve the data in a 'multipart/form-data' form
if (grep("^multipart", request$c.type)) {
pars <- parse.multipart()
} else {
}
# Create the data frame
try(MyDF <- read.table(file = textConnection(pars$MyTable), header = FALSE,
sep = "\t"))
# HTML output
if (!exists("MyDF")) {
out("<h2>Something went wrong…</h2>",
"<p>Make sure your table has the same number of elements for each ",
"row.</p>", sep = "", eol = "")
} else {
out("<h2>Your data frame</h2><p>This is your data frame.</p>")
oprint(MyDF)
oprint(sapply(MyDF, class))
}
out("</body></html>")
done()
}
To run this script, go here : http://localhost/cgi-bin/R/tablesubmit
Testing
Copy and paste the data from à spreadsheet (either LibreOffice Calc or Excel). The non-ASCII characters are handled correctly if the users did not change their browser encoding. You may want to use the options read.table() such as sep, col.names or colClasses.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series,ecdf, trading) and more...


Zero Inflated Models and Generalized Linear Mixed Models with R.
Zuur, Saveliev, Ieno (2012).