R: Entering Data

I. Introduction

One of the most basic things one usually needs to know when using R, is how does one get data into R so that you can analyze it. This page will give you some basic functions that you can use to simply get data into R.

II. Entering Data Using "c"

There are a variety of ways to get data into R, but if your dataset is small, manually entering the data is rather straightforward using the c() function. It’s easiest just to think that c stands for combine.

Example 1

Enter the following dataset into R: {11, 14, 22, 15}.  We will label the data my.data

R CODE

my.data=c(11,14,22,15) #this code will create your dataset and assign it the variable name my.data
my.data #If you want to know what a variable holds, you must ask for it by name

R OUTPUT

[1]  11  14  22  15
Common Issues

Common Mistakes:

1. Forgetting to use c

x=(1,2,3) ## INCORRECT
x=c(1,2,3) ### CORRECT

2. Missing a comma while entering data

x=(1 2,3) ## INCORRECT
x=c(1,2,3) ### CORRECT

III. Using ":"

Using “:“, one is able to quickly create a sequence of numbers, incremented by 1.

Example 1

Create a list of numbers 1 through 5, assign the name stats.data to your data.

R INPUT

stats.data=1:5   #this code will create your sequence of data from 1 to 5, by increments of 1
stats.data   # if you wish to view the data, don't forget to ask for the data by name

R OUTPUT

[1]  1  2  3  4  5
Example 2

Create a list of numbers 5 through -6, assign the name decreasing.data to your data.

R INPUT

decreasing.data=5:-6   #this code will create your sequence of data from 5 to -6, by increments of 1
decreasing.data   # if you wish to view the data, don't forget to ask for the data by name

R OUTPUT

[1]  5  4  3  2  1  0  -1  -2  -3  -4  -5  -6

IV. Using seq() Function

The seq(from, to, by) function creates a sequence of numbers between any two numbers incremented by a specific number. Also, The seq(from, to, length.out) function creates a sequence of numbers with a specific length between any two numbers.

Example 1

Create a sequence of numbers from 1 through 3, with increments of 0.5, save as z.

R CODE

z=seq(1,3,0.5)   # seq(low.number, high.number, increment.size)
z

R OUTPUT

[1]  1.0  1.5  2.0  2.5  3.0
Example 2

Create a sequence of numbers with length 6 from 0 through 12.

R CODE

seq(0, 12, length.out=6)

R OUTPUT

[1]   0.0    2.4    4.8    7.2    9.6   12.0
Copyright © 2013 STATS4STEM.ORG. All rights reserved.