Site de Jean-Michel RICHER

Maître de Conférences en Informatique à l'Université d'Angers

Ce site est en cours de reconstruction certains liens peuvent ne pas fonctionner ou certaines images peuvent ne pas s'afficher.


5.1. Input from code, keyboard, CSV or Table

Imagine you have the following data that you want to process:

 age   gender   weight 
 25   male   160 
 30   female   110 
 56   male   220 
Persons

5.1.1. Define data from R code

You can define them writing R code like this:

# create a data frame from scratch 
age <- c(25, 30, 56)
gender <- c("male", "female", "male")
weight <- c(160, 110, 220) 
mydata <- data.frame(age,gender,weight)

5.1.2. Enter data from keyboard

Or you can define a data frame that you can later fill with the edit() function:

# enter data using editor 
mydata <- data.frame(age=numeric(0), gender=character(0), weight=numeric(0))
# make assignment to save data
mydata <- edit(mydata)
# save in a file
> save(mydata,file="mydata.Rdata")

If you need to read data from keyboard, you could use something like this:

> num = as.integer(readline(prompt="Enter a number: "))
Enter a number: a
Warning message:
NAs introduced by coercion 
> num
[1] NA
> num = as.integer(readline(prompt="Enter a number: "))
Enter a number: 1234
> num
[1] 1234
> num = scan(what=integer())
1: 1
2: 2
3: 89
4: -75           
# use Ctrl-D to stop reading
5: Read 4 items  
> num
[1]   1   2  89 -75

5.1.3. From file

You can put the data in a file either a table or a CSV file as follows.

5.1.3.a  Define data as a table

If you define the data as a table use the space as a separator and let's call the file mydata.RData:

# you can introduce comments using '#' as first character
age gender weight
25 male   160
30 female 110
56 male   220

Then you can read the table with the read.table() method, don't forget to set the header = T in order for the first line of the file to be considered as the names of the columns and not part of the data.

mydata <- read.table("mydata.RData", header = T)
> mydata
  age gender weight
1  25   male    160
2  30 female    110
3  56   male    220

5.1.3.b  Define data as a CSV (Comma Separated Values) file


age, gender, weight
25, male,   160
30, female, 110
56, male,   220

Then you can read the file using the read.csv() method and the first line will be considered as the header.

mydata <- read.csv("mydata.csv")
> mydata
  age gender weight
1  25   male    160
2  30 female    110
3  56   male    220