How to Copy and Paste Data into R from the Clipboard

How do I copy and paste data into R from the clipboard?

Assuming you have data in the Windows clipboard (for example, copied data from Excel), to put that data into a variable named copdat in R use:

copdat <- read.delim("clipboard")

If you want to copy data from an R variable named rdat into the Windows clipboard (for example, to copy into Excel) use:

write.table(rdat, "clipboard", sep="\t", row.names=FALSE, col.names=FALSE)

Copy and paste data into R

First, copy (e.g. "⌘ + C") the data set.

Then, paste (e.g. "⌘ + V") to create an R character vector:

x <- " A B C D
1: 2 2 5 3
2: 2 1 2 3
3: 3 4 4 3"

Next, use the read.table() function:

y <- read.table(text = x, header = TRUE)

Done! The data is now in a data frame:

class(y)
[1] "data.frame"

You might also want to check out the dput() function which writes an ASCII text representation of an R object that you can paste into your StackOverflow question or answer.

R: Is it possible to 'copy/paste' data into R?

This is easy in base R with the text= argument of read.table: you need to specify header=TRUE (to indicate that the first row is the column names) and row.names=1 (to indicate that the first column is the row names). It's convenient to put the optional arguments first, "out of order", so that they're visible above the big block of text.

my_data <- read.table(header=TRUE,
row.names = 1,
text="
weight height age
1 2998.958 15.26611 53
2 3002.208 18.08711 52
3 3008.171 16.70896 49
4 3002.374 17.37032 55
5 3000.658 18.04860 50
6 3002.688 17.24797 45
7 3004.923 16.45360 47
8 2987.264 16.71712 47
9 3011.332 17.76626 50
10 2983.783 18.10337 42
11 3007.167 18.18355 50
12 3007.049 18.11375 53
13 3002.656 15.49990 42
14 2986.710 16.73089 47
15 2998.286 17.12075 52
")

How to copy a plot into the clipboard for pasting?

Tested on Edge.

library(shiny)
library(ggplot2)

js <- '
async function getImageBlobFromUrl(url) {
const fetchedImageData = await fetch(url);
const blob = await fetchedImageData.blob();
return blob;
}
$(document).ready(function () {
$("#copybtn").on("click", async () => {
const src = $("#plotDF>img").attr("src");
try {
const blob = await getImageBlobFromUrl(src);
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
alert("Image copied to clipboard!");
} catch (err) {
console.error(err.name, err.message);
alert("There was an error while copying image to clipboard :/");
}
});
});
'

ui <- fluidPage(
tags$head(
tags$script(HTML(js))
),
br(),
actionButton("copybtn", "Copy", icon = icon("copy"), class = "btn-primary"),
br(),
plotOutput("plotDF")
)

server <- function(input, output, session){

output[["plotDF"]] <- renderPlot({
ggplot(
iris, aes(x = Sepal.Length, y = Sepal.Width)
) + geom_point()
})

}

shinyApp(ui, server)

Sample Image



EDIT

Alerts are not nice. I suggest shinyToastify instead.

library(shiny)
library(shinyToastify)
library(ggplot2)

js <- '
async function getImageBlobFromUrl(url) {
const fetchedImageData = await fetch(url);
const blob = await fetchedImageData.blob();
return blob;
}
$(document).ready(function () {
$("#copybtn").on("click", async () => {
const src = $("#plotDF>img").attr("src");
try {
const blob = await getImageBlobFromUrl(src);
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
Shiny.setInputValue("success", true, {priority: "event"});
} catch (err) {
console.error(err.name, err.message);
Shiny.setInputValue("failure", true, {priority: "event"});
}
});
});
'

ui <- fluidPage(
tags$head(
tags$script(HTML(js))
),
useShinyToastify(),
br(),
actionButton("copybtn", "Copy", icon = icon("copy"), class = "btn-primary"),
br(),
plotOutput("plotDF")
)

server <- function(input, output, session){

output[["plotDF"]] <- renderPlot({
ggplot(
iris, aes(x = Sepal.Length, y = Sepal.Width)
) + geom_point()
})

observeEvent(input[["success"]], {
showToast(
session,
input,
text = tags$span(
style = "color: white; font-size: 20px;", "Image copied!"
),
type = "success",
position = "top-center",
autoClose = 3000,
pauseOnFocusLoss = FALSE,
draggable = FALSE,
style = list(
border = "4px solid crimson",
boxShadow = "rgba(0, 0, 0, 0.56) 0px 22px 30px 4px"
)
)
})

observeEvent(input[["failure"]], {
showToast(
session,
input,
text = tags$span(
style = "color: white; font-size: 20px;", "Failed to copy image!"
),
type = "error",
position = "top-center",
autoClose = 3000,
pauseOnFocusLoss = FALSE,
draggable = FALSE,
style = list(
border = "4px solid crimson",
boxShadow = "rgba(0, 0, 0, 0.56) 0px 22px 30px 4px"
)
)
})

}

shinyApp(ui, server)

Sample Image

How do I copy a complete data frame object to clipboard?

Although I haven't tried it myself, clipr seems to do what you want.

library(shiny)
library(clipr)
library(rhandsontable)

ui <- fluidPage(
actionButton(inputId = 'click',label = 'COPY'),
p('Click COPY and paste the results below witch Ctrl+V.'),
rHandsontableOutput('rhot')
)

server <- function(input, output, session) {


output$rhot = renderRHandsontable({
df = data.frame(lapply(1:10, function(x){rep('',10)}))
colnames(df) = paste('c',1:10)
rhandsontable(df)
})

observeEvent(input$click,{
clipr::write_clip(mtcars)
})

}

shinyApp(ui, server)

How can I read data from the clipboard into R on a Unix system?

If you look at other StackOverflow questions such as this one, you see xclip suggested as well as two handy aliases

alias setclip="xclip -selection c"
alias getclip="xclip -selection c -o"

which give a strong hint as to how this works. To test, I installed xclip (which is available for Ubuntu which I run), highlighted three lines from the R start up text and tried it:

edd@rob:~$ xclip -selection c -o
R version 4.0.3 (2020-10-10) -- "Bunny-Wunnies Freak Out"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

edd@rob:~$

Works as advertised: xclip recovers the clipboard content, and prints it to stdout.

To use this in R, we simply need to read from that output which we can via the pipe() connection:

> res <- readLines(pipe("xclip -selection c -o"))
> str(res)
chr [1:19] "" ...
> res[1:3]
[1] ""
[2] "R version 4.0.3 (2020-10-10) -- \"Bunny-Wunnies Freak Out\""
[3] "Copyright (C) 2020 The R Foundation for Statistical Computing"
>

But even that is overkill. Looking at ??clipboard suggests help(connections) which has an entire paragraph (!!) about this which includes

 ‘file’ can be used with ‘description = "clipboard"’ in mode ‘"r"’
only. This reads the X11 primary selection (see <URL:
https://specifications.freedesktop.org/clipboards-spec/clipboards-latest.txt>),
which can also be specified as ‘"X11_primary"’ and the secondary
selection as ‘"X11_secondary"’. On most systems the clipboard
selection (that used by ‘Copy’ from an ‘Edit’ menu) can be
specified as ‘"X11_clipboard"’.

and indeed:

> res2 <- readLines(file(description="clipboard"))
Warning message:
In readLines(file(description = "clipboard")) :
incomplete final line found on 'clipboard'
> str(res2)
chr [1:19] "" ...
> res2[1:3]
[1] ""
[2] "R version 4.0.3 (2020-10-10) -- \"Bunny-Wunnies Freak Out\""
[3] "Copyright (C) 2020 The R Foundation for Statistical Computing"
>

Seemingly, you would still need xclip to write to the clipboard from R.



Related Topics



Leave a reply



Submit