Frequently Asked Questions

I can't get my datafile to read in

First have a look to see what did read in, e.g. by typing

fix(data.frame)

Where data.frame is the name of the dataframe into which you'd hoped the data been read.

The easiest kind of data to read into R is either comma separated ("csv") or tab delimited (usually "txt"). If you open the dataset in, say, notepad, then it will look like the following if it's comma separated

Variable1,Variable2,Variable3
1,2,5
5,3,2
4,2,6

and something like the following if it's tab delimited

Variable1    Variable2    Variable3
1    2    5
5    3    2
4    2    6

To read in comma separated files, use

data.frame.name <- read.table("filename.csv", sep=",", header=TRUE)

and tab separated, use

data.frame.name <- read.table("filename.txt", sep="\t", header=TRUE)

("/t" is the code for a tab character in R.) Here data.frame.name is the dataframe you want to create and filename.xxx is the filename.

The first argument to read.table is the filename. But which folder is this file in? Unless you give the absolute path, R will look for the file in the current working directory. So if you get an error message that there is 'No such file or directory' it is most likely your current working directory needs to be changed.

getwd()                # What is your current working directory?
setwd("C:/workspace")  # Set your current working directory

You can also change the working directory by clicking on the console window in the R GUI, and then selecting "Change dir…" from the File menu.

Once you can open and read the file, look at the dimensions of the object you have read. If they don't seem to make sense it is likely you have not told R how the columns of data in the file are separated.

x = read.table("filename.txt", sep="\t", header=TRUE)
dim(x)        # What dimensions (number of rows and columns) ?
sapply(x, class) # What class of vector is in each column of your data frame?

How can I copy data to and from the clipboard?

The short answer: pretend there's a file named "clipboard" and write to and read from it.

This example sticks data into the clipboard:

some.data = data.frame(x = 1:10, y = (1:10)^2) # generate some data
some.data
write.table(some.data, "clipboard", sep="\t", row.names=F)

(Try running it, and then pasting into, say, Excel.)

This example reads data from the clipboard again:

more.data = read.table("clipboard", sep="\t", header=T)
more.data
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License