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.
Imagine you have the following data that you want to process:
| age | gender | weight |
|---|---|---|
| 25 | male | 160 |
| 30 | female | 110 |
| 56 | male | 220 |
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)
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
You can put the data in a file either a table or a CSV file as follows.
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
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