R from scratch (2) — data frames, reading a .csv, your own functions and packages (and the read.csv that turned my marks into a mess)

A data frame is a table in which every column is a vector: if you got the hang of vectors in the first part, you already know how to do almost everything you will need with ME1 data.

I exported my first lab .csv from Excel with Spanish settings: columns separated by semicolons and decimals with a comma. I read it with read.csv, asked for the mean of the marks and R answered with an NA and a warning: the argument was not numeric. The marks were there, plain to see in Excel, but for R that table had a single column with a very strange name and almost everything NA. It took me a good while to understand what R had read. The fix was adding a 2, and I tell you about it below.

This is the second part of R from scratch. In the first we saw the console, variables, vectors and matrices. Here come lists, factors, data frames, how to read and save .csv files, how to write your own functions and how packages work. Every output is the real one.

Before you start. All you need is what we saw in the first part: creating a vector with c(), getting elements out with brackets and filtering with a condition that gives TRUE or FALSE, like marks >= 5. If that rings a bell, you are fine. The article has three blocks, in this order: first, the structures that hold data (the list, the factor and, above all, the data frame, which is a table made of vectors); then, how to get those tables in and out of a .csv file, with the scare from my story; and finally, how to write your own functions and how to use other people’s through packages. Almost everything revolves around the same table: six students, their group, their study hours and their mark. If at any point you get lost, go back to it and ask yourself which row or which column you are touching.

Lists: a box with different things

A vector only holds values of the same type. When you need to put different things together (a name, a vector of marks and a TRUE), you use a list:

student <- list(name = "Lucía", marks = c(6.5, 8), passed = TRUE)
student$name
student$marks
student[["passed"]]
str(student)

Output:

[1] "Lucía"
[1] 6.5 8.0
[1] TRUE
List of 3
 $ name  : chr "Lucía"
 $ marks : num [1:2] 6.5 8
 $ passed: logi TRUE

Each element has a name and you get it with $ (or with double brackets [[ ]]). str() («structure») shows at a glance what is inside and what type each thing is; you will use it a lot.

Why tell you about lists if you will hardly create them yourself? Because many statistics functions return lists. When you run a t.test() in ME1, the result is a list and result$p.value is how you get the p-value out.

One bracket or two: what each one gives you

Above you have seen two ways of getting an element out of the list, $ and [[ ]]. There is a third one, the single bracket, which looks very similar and does not do the same thing. The question that settles it is this: do you want what is inside the box, or a piece of the box?

student["marks"]       # single bracket: a smaller list
student[["marks"]]     # double bracket: what is inside

Output:

$marks
[1] 6.5 8.0

[1] 6.5 8.0
What you writeWhat you getWhy
student$marksThe vector 6.5 8.0$ opens the box and takes out what it stores under that name
student[["marks"]]The vector 6.5 8.0The same as $, but with the name in quotes: it also works if you have the name stored in a variable
student["marks"]A list with a single element, marksThe single bracket trims the box: it gives you a smaller box, not what is inside

You can see the difference in the output: the first one has $marks above the numbers, which is R’s way of telling you «this is still a list». And since it is still a list, you cannot do calculations with it: mean(student["marks"]) gives NA and a warning, while mean(student[["marks"]]) gives 7.25.

Check you’ve got it: what does student$marks[2] return?

It returns 8. You read it from left to right: first student$marks opens the box and takes out the vector c(6.5, 8); then you ask that vector for its element 2 with a single bracket, as in the first part. First you open the box, then you choose inside it.

Factors: qualitative variables

In statistics we distinguish quantitative variables (numbers you operate with, like the mark) and qualitative ones (categories, like the lab group). In R, qualitative variables are stored as factors:

group <- c("A", "B", "A", "A", "B", "C", "A")
f <- factor(group)
f
levels(f)                  # the distinct categories
table(f)                   # absolute frequencies
prop.table(table(f))       # relative frequencies

Output:

[1] A B A A B C A
Levels: A B C
[1] "A" "B" "C"
f
A B C 
4 2 1 
f
        A         B         C 
0.5714286 0.2857143 0.1428571 

A factor is a vector that knows which categories are possible (its levels, Levels). table() counts how many times each appears: it is the absolute frequency table from the descriptive statistics topic. And prop.table() divides each by the total: A appears 4 times out of 7, 4 / 7 = 0.571.

The last two lines, with the count for each category in plain sight:

CategoryTimes (table)Proportion (prop.table)Why
A44 / 7 = 0.57It appears in positions 1, 3, 4 and 7 of the vector
B22 / 7 = 0.29Positions 2 and 5
C11 / 7 = 0.14Only in position 6
Total70.57 + 0.29 + 0.14 = 1Proportions always add up to 1: it is the quick way to check nothing has slipped through

Passing the factor straight to prop.table. prop.table(f) gives the error ‘sum’ not meaningful for factors: prop.table divides each number by the sum, and letters cannot be added up. First you count with table() and then you divide: prop.table(table(f)).

If the categories have a natural order (low, medium, high), tell R with levels and ordered = TRUE. That way it orders them properly and lets you compare them:

level <- factor(c("Medium", "High", "Low", "Medium"),
                levels = c("Low", "Medium", "High"), ordered = TRUE)
level
table(level)
level[1] < level[2]

Output:

[1] Medium High   Low    Medium
Levels: Low < Medium < High
level
   Low Medium   High 
     1      2      1 
[1] TRUE

Without levels, R would sort the categories alphabetically (High, Low, Medium), which makes no sense for an ordinal variable.

Data frames: the data table

A data frame is the structure you will work with in every lab: a table in which each row is an observation (a student) and each column is a variable (their study hours, their mark). Each column is a vector, so everything you know about vectors still applies.

The parts of a data frameThe study data frame with 4 columns and 4 rows; the mark column highlighted in coral and row 2 in violet.studystudentgrouphoursmark1AnaA107.52BeaB45.03CarlosA76.04DaniB129.0study[2, ]a row = an observation (a student)df[row, column]as in matricesblank = allstudy$marka column = a variable(a vector)
Each column is a vector of a single type; each row brings together one student's data.
study <- data.frame(
  student = c("Ana", "Bea", "Carlos", "Dani", "Eva", "Fran"),
  group   = factor(c("A", "B", "A", "B", "A", "B")),
  hours   = c(10, 4, 7, 12, 3, 8),
  mark    = c(7.5, 5, 6, 9, 4, 6.5)
)
study
str(study)
dim(study)

Output:

  student group hours mark
1     Ana     A    10  7.5
2     Bea     B     4  5.0
3  Carlos     A     7  6.0
4    Dani     B    12  9.0
5     Eva     A     3  4.0
6    Fran     B     8  6.5
'data.frame':	6 obs. of  4 variables:
 $ student: chr  "Ana" "Bea" "Carlos" "Dani" ...
 $ group  : Factor w/ 2 levels "A","B": 1 2 1 2 1 2
 $ hours  : num  10 4 7 12 3 8
 $ mark   : num  7.5 5 6 9 4 6.5
[1] 6 4

str() is your best friend again: it tells you there are 6 observations (obs.) of 4 variables and the type of each one (chr text, Factor qualitative, num number). Look at it always after reading some data: it is what would have saved me the scare in the story.

Why a matrix is not enough

A fair question before moving on: if we already saw matrices in the first part, and they also have rows and columns, why another structure? Let’s try it with two columns of the table, the name and the hours:

student <- c("Ana", "Bea", "Carlos", "Dani", "Eva", "Fran")
hours <- c(10, 4, 7, 12, 3, 8)
m <- cbind(student, hours)   # a matrix with the two columns
m[1:2, ]
mean(m[, "hours"])

Output:

     student hours
[1,] "Ana"   "10" 
[2,] "Bea"   "4"  
[1] NA
Warning message:
In mean.default(m[, "hours"]) :
  argument is not numeric or logical: returning NA

The quotes around "10" and "4" give it away. A matrix is a single vector folded into rows and columns, so everything inside it has to be of the same type. When you mix names and numbers, R turns the numbers into text, and you cannot take the mean of text: you get NA and a warning, the same warning as in my story.

The data frame solves exactly that. Each column is its own vector and has its own type: the hours are still numbers even though there are names next to them. With that idea in mind, look again at the data.frame() above and read it for what it is: four vectors of the same length, one per column, placed side by side. That is why str() can tell you a different type for each column.

Picking columns, rows and cells

There are two ways to reach the data: $ for a column, and the brackets [row, column] as in matrices.

study$mark                                    # a column (a vector)
study[2, ]                                    # the whole of row 2
study[, c("student", "mark")]                 # two columns by name
study[study$mark >= 6, ]                      # rows that meet a condition
study[study$group == "A" & study$hours > 5, "student"]

Output:

[1] 7.5 5.0 6.0 9.0 4.0 6.5
  student group hours mark
2     Bea     B     4    5
  student mark
1     Ana  7.5
2     Bea  5.0
3  Carlos  6.0
4    Dani  9.0
5     Eva  4.0
6    Fran  6.5
  student group hours mark
1     Ana     A    10  7.5
3  Carlos     A     7  6.0
4    Dani     B    12  9.0
6    Fran     B     8  6.5
[1] "Ana"    "Carlos"

The fourth line is the filter from the first part applied to a table: study$mark >= 6 gives a TRUE or FALSE per row, and the brackets keep the TRUE rows (and all the columns, hence the comma with the gap after it). In the last one, & means «and»: students in group A and with more than 5 hours. Only Ana (10 h) and Carlos (7 h) qualify; Eva is in group A, but she studied 3 hours.

What you writeWhat you get
df$colThe column col (a vector)
df[i, ]Row i
df[, "col"]The column col
df[cond, ]The rows that meet the condition
df[cond, "col"]That column for those rows

Forgetting the comma when filtering rows. study[study$mark >= 6] without the comma does not filter rows: R reads it as columns and complains with undefined columns selected. For rows, always [condition, ].

The filter, row by row

The last line of the code above does three things at once. Unfolded for each student, you can see what each condition decides:

RowStudentgroup == "A"hours > 5With &Why
1AnaTRUETRUE (10)TRUEMeets both
2BeaFALSEFALSE (4)FALSEMeets neither
3CarlosTRUETRUE (7)TRUEMeets both
4DaniFALSETRUE (12)FALSEStudies a lot, but is in group B: with & one failure is enough
5EvaTRUEFALSE (3)FALSEIs in group A, but does not reach 5 hours
6FranFALSETRUE (8)FALSEThe same case as Dani

The «With &» column, TRUE FALSE TRUE FALSE FALSE FALSE, is what goes before the comma: it picks rows 1 and 3. What goes after the comma, "student", picks the column. That is why you get a vector with two names and not a table: you asked for a single column.

If instead of «and» you want «or», the symbol is the vertical bar: with study$group == "A" | study$hours > 5 meeting one of the two is enough, and everyone gets in except Bea.

Check you’ve got it: what does study[study$mark < 6, “student”] return?

It returns "Bea" "Eva". The condition study$mark < 6 gives TRUE only in row 2 (Bea, a 5) and in row 5 (Eva, a 4). Before the comma those two rows are picked, and "student" keeps the column of names. Carlos, with exactly a 6, does not get in: < 6 leaves the 6 out (to include it you would need <=).

Adding columns and summarising

A new column is created by assigning it with $. And to summarise by group there is tapply():

study$passed <- study$mark >= 5
study
mean(study$mark)
tapply(study$mark, study$group, mean)
summary(study[, c("hours", "mark")])
cor(study$hours, study$mark)

Output:

  student group hours mark passed
1     Ana     A    10  7.5   TRUE
2     Bea     B     4  5.0   TRUE
3  Carlos     A     7  6.0   TRUE
4    Dani     B    12  9.0   TRUE
5     Eva     A     3  4.0  FALSE
6    Fran     B     8  6.5   TRUE
[1] 6.333333
       A        B 
5.833333 6.833333 
     hours             mark      
 Min.   : 3.000   Min.   :4.000  
 1st Qu.: 4.750   1st Qu.:5.250  
 Median : 7.500   Median :6.250  
 Mean   : 7.333   Mean   :6.333  
 3rd Qu.: 9.500   3rd Qu.:7.250  
 Max.   :12.000   Max.   :9.000  
[1] 0.9896567

tapply(values, groups, function) applies the function to each group separately: the mean of A is (7.5 + 6 + 4) / 3 = 5.833 and that of B, (5 + 9 + 6.5) / 3 = 6.833. summary() on several numeric columns gives the summary of each, and cor() measures the linear relationship between hours and mark: 0.99 is very close to 1, so in these (made-up, of course) data, more hours, higher mark.

What tapply does inside, in three steps:

  1. Split the marks according to each row’s group: A keeps 7.5, 6 and 4 (Ana, Carlos and Eva) and B keeps 5, 9 and 6.5 (Bea, Dani and Fran). It knows which mark goes with which group because both columns are in the same order: row 1 is Ana in both.
  2. Apply the function to each piece: the mean of A is 17.5 / 3 = 5.83 and that of B, 20.5 / 3 = 6.83.
  3. Combine the results into a vector, with each group’s name on top: that is why the output has A and B on its first line.

If you swap mean for another function, only step 2 changes: tapply(study$mark, study$group, max) gives the highest mark in each group, 7.5 in A and 9 in B.

Misspelling a column name. study$Mark (with a capital) gives no error: it returns NULL, and the failure shows up later with a message that has nothing to do with it. If a column «does not exist», look at names(study).

Reading a .csv file

In the labs, data are not typed in by hand: they come in a file. The most common format is CSV (comma-separated values), a text with one row per line and the columns separated by commas. This is study.csv:

student,group,hours,mark
Ana,A,10,7.5
Bea,B,4,5
Carlos,A,7,6
Dani,B,12,9
Eva,A,3,4
Fran,B,8,6.5

You read it with read.csv(), which returns a data frame:

dat <- read.csv("study.csv")
head(dat, 3)          # the first 3 rows
str(dat)

Output:

  student group hours mark
1     Ana     A    10  7.5
2     Bea     B     4  5.0
3  Carlos     A     7  6.0
'data.frame':	6 obs. of  4 variables:
 $ student: chr  "Ana" "Bea" "Carlos" "Dani" ...
 $ group  : chr  "A" "B" "A" "B" ...
 $ hours  : int  10 4 7 12 3 8
 $ mark   : num  7.5 5 6 9 4 6.5

read.csv assumes the first line holds the column names (header = TRUE), that the separator is the comma and that decimals use a point. Notice that group comes out as chr (text), not as a factor: since R 4.0, text stays as text. If you want it as a factor, dat$group <- factor(dat$group). And hours comes out as int: all its values are whole numbers, so R stores them as integers, which for calculations is the same as num.

The Spanish-style .csv (the story)

Now the file from my story. Excel with Spanish settings separates columns with semicolons and writes decimals with a comma:

student;group;hours;mark
Ana;A;10;7,5
Bea;B;4;5
Carlos;A;7;6
Dani;B;12;9
Eva;A;3;4
Fran;B;8;6,5

If I read it with read.csv, this happens:

bad <- read.csv("study-es.csv")
bad
str(bad)

Output:

             student.group.hours.mark
Ana;A;10;7                          5
Bea;B;4;5                          NA
Carlos;A;7;6                       NA
Dani;B;12;9                        NA
Eva;A;3;4                          NA
Fran;B;8;6                          5
'data.frame':	6 obs. of  1 variable:
 $ student.group.hours.mark: int  5 NA NA NA NA 5

Since read.csv looks for commas and there are none in the header, the whole first line becomes the name of a single column (student.group.hours.mark: R swaps the ; for dots). In the rows with a decimal comma (Ana’s and Fran’s), that comma splits the line in two: what comes before ends up as a row name and what comes after, the 5 from 7,5 or 6,5, as the only value. The other rows are left as NA. And the worst part: not a single error. That is what happened to me. The fix is read.csv2, the «European» version, which uses ; as separator and , as decimal:

Reading a Spanish CSV: read.csv versus read.csv2A file with semicolons and decimal commas: read.csv gives one odd column full of NA; read.csv2 gives the 4 columns right.study-es.csvstudent;group;hours;markAna;A;10;7,5Bea;B;4;5separates with ; and decimals with ,read.csv()read.csv2()1 odd columnalmost all NA4 columnsmark is numread.csv expects "," between columns and "." for decimals; read.csv2, ";" and ",".
Look at the first line of the file before choosing the function: the separator tells you everything.
good <- read.csv2("study-es.csv")
str(good)
mean(good$mark)

Output:

'data.frame':	6 obs. of  4 variables:
 $ student: chr  "Ana" "Bea" "Carlos" "Dani" ...
 $ group  : chr  "A" "B" "A" "B" ...
 $ hours  : int  10 4 7 12 3 8
 $ mark   : num  7.5 5 6 9 4 6.5
[1] 6.333333

Now it works: 6 rows, 4 columns and mark is num. The mean, (7.5 + 5 + 6 + 9 + 4 + 6.5) / 6 = 38 / 6 = 6.333, comes out right.

FunctionSeparatorDecimalWhen
read.csv(),.The «international» CSV
read.csv2();,The CSV from Excel in Spanish (and other European settings)
read.table(sep = ..., dec = ...)Whatever you sayWhatever you sayAny other case (tabs, spaces…)

Before reading a file, open it with Notepad (not with Excel, which shows it already converted) and look at the first line: you will see whether it separates with , or with ;.

What read.csv saw, line by line

Now that it works, go back for a moment to the strange output from before. Every number has an explanation if you put yourself in the place of read.csv, which only knows how to cut at commas:

Line of the filePieces when cutting at commasWhat R doesWhy
student;group;hours;mark1: the whole lineTurns it into the name of the only column, student.group.hours.markIt is the header, and ; is not valid in a column name: R swaps it for a dot
Ana;A;10;7,52: Ana;A;10;7 and 5The first piece becomes the row name and the 5 is the valueThere is one more piece than column names, and in that case R assumes the first one is the row name
Bea;B;4;51: the whole lineThe line is the row name and the value is left as NAThere is no comma at all, so nothing is left for the column

Carlos, Dani and Eva follow Bea’s path, and Fran follows Ana’s. The column comes out as int because the only values left, the two 5s, are whole numbers. And since for R there is no mark column at all, bad$mark is NULL and mean(bad$mark) gives NA with the warning that the argument is not numeric: exactly what happened to me.

Check you’ve got it: if in the Spanish file all the marks were whole numbers (a 7 instead of 7,5 and a 6 instead of 6,5), what would read.csv give?

No line would have commas, so each one would stay as a single piece. Since they all have as many pieces as the header, there are no row names any more: you get a single column, student.group.hours.mark, of type chr, with each whole line as text ("Ana;A;10;7", "Bea;B;4;5"…). Not a single NA and not a single error, which is even more treacherous. What saves you once again is str(): 6 obs. of 1 variable tells you something is wrong, because you expected 4 variables.

Where R looks for the file

If the file is not in the folder where R is looking, this happens:

read.csv("final_marks.csv")

Output:

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'final_marks.csv': No such file or directory

That folder is the working directory. getwd() tells you which it is and setwd("path") changes it. In RStudio the most comfortable way is to work with a project or use Session > Set Working Directory, as I explain in the guide on how to use RStudio. In the site’s R playground you do not need it: the files you create at the top are already in the working folder.

Saving a data frame

For the way back there is write.csv(). With row.names = FALSE it does not write the column of row numbers, which you almost never want:

write.csv(study, "study-final.csv", row.names = FALSE)
readLines("study-final.csv")     # the file, line by line

Output:

[1] "\"student\",\"group\",\"hours\",\"mark\",\"passed\""
[2] "\"Ana\",\"A\",10,7.5,TRUE"                          
[3] "\"Bea\",\"B\",4,5,TRUE"                             
[4] "\"Carlos\",\"A\",7,6,TRUE"                          
[5] "\"Dani\",\"B\",12,9,TRUE"                           
[6] "\"Eva\",\"A\",3,4,FALSE"                            
[7] "\"Fran\",\"B\",8,6.5,TRUE"                          

readLines() reads a file as text, one line per element. Here it is useful to check what has been written: the passed column we added earlier is there too.

Your own functions

When a calculation repeats, it is worth putting it in a function. You already use many (mean, sd, table); writing your own is just as simple:

The parts of an R functionThe sample_variance function with its name, its argument x, its body in braces and the last line, which is what it returns.sample_variance <- function(x) {n <- length(x)sum((x – mean(x))^2) / (n – 1)}name: stored likeany variablex: the data it receivesthe last line iswhat it returnssample_variance(c(7.5, 5, 6, 9, 4, 6.5)) → 3.166667
When you call it with the marks, x takes the marks and the function returns the result of the last line.
sample_variance <- function(x) {
  n <- length(x)
  sum((x - mean(x))^2) / (n - 1)    # the last line is what it returns
}
sample_variance(study$mark)
var(study$mark)

Output:

[1] 3.166667
[1] 3.166667

The parts of the function, as in the drawing:

  • sample_variance is the name: the function is stored in a variable, just like a number.
  • function(x) says it receives one piece of data, which inside the function will be called x. When you call sample_variance(study$mark), x holds the marks.
  • The body goes between braces. The function returns the value of the last line (you can also write return(...) explicitly).
  • n is a local variable: it exists while the function runs and disappears afterwards.

The function from the inside, step by step. This is what happens, line by line, when you call sample_variance(study$mark):

StepWhat is calculatedValueWhy
1x7.5 5.0 6.0 9.0 4.0 6.5It is the argument: inside the function, x takes the value of the marks
2n <- length(x)6There are six marks
3mean(x)6.3338 / 6 = 6.33
4x - mean(x)1.17 -1.33 -0.33 2.67 -2.33 0.17Subtracts the mean from every mark at once, with no loop: it is a vector operation, as in the first part
5(x - mean(x))^21.36 1.78 0.11 7.11 5.44 0.03Squared, so that the negative distances do not cancel out the positive ones
6sum(...)15.83The six squares are added up
7/ (n - 1)3.1715.83 / 5 = 3.17. Dividing by n − 1 and not by n is what makes it the sample variance. It is the last line, so it is what the function returns

When the function finishes, n and all these intermediate calculations disappear; outside, only the result is left, the 3.166667 in the output.

Check you’ve got it: what does sample_variance(c(2, 4, 9)) return?

It returns 13. Step by step: n is 3; the mean is (2 + 4 + 9) / 3 = 15 / 3 = 5; the differences from the mean are −3, −1 and 4; their squares, 9, 1 and 16, add up to 26; and 26 / (3 − 1) = 26 / 2 = 13. If you got 8.67, you divided by n = 3 instead of by n − 1 = 2.

It matches var(), which is exactly what we wanted to check. Now one with an argument with a default value and a result with names:

summary_stats <- function(x, digits = 2) {
  r <- c(mean = mean(x), median = median(x), std_dev = sd(x))
  round(r, digits)
}
summary_stats(study$mark)
summary_stats(study$hours, digits = 1)

Output:

   mean  median std_dev 
   6.33    6.25    1.78 
   mean  median std_dev 
    7.3     7.5     3.4 

If you say nothing, digits is 2; if you give it, yours is used. R’s functions work like this too: round(x) rounds to 0 decimals because that is the default value of its second argument.

Deciding and repeating: if and for

Inside a function you can decide with if and else:

grade <- function(mark) {
  if (mark >= 9) {
    "Outstanding"
  } else if (mark >= 7) {
    "Very good"
  } else if (mark >= 5) {
    "Pass"
  } else {
    "Fail"
  }
}
grade(7.5)
sapply(study$mark, grade)
for (i in 1:3) cat(study$student[i], "->", grade(study$mark[i]), "\n")

Output:

[1] "Very good"
[1] "Very good"   "Pass"        "Pass"        "Outstanding"
[5] "Fail"        "Pass"       
Ana -> Very good 
Bea -> Pass 
Carlos -> Pass 

grade receives one mark. To apply it to all of them, sapply(vector, function) calls it with each element and puts the results together in a vector. The for does the same by hand for the first three rows. In R people tend to use vectorised functions and sapply instead of loops, because you write less and make fewer mistakes; but the for exists, and sometimes it is the clearest option.

if looks at a single value. If you write if (study$mark >= 5) with a whole vector, R 4.2 or later gives an error (the condition has length > 1). To decide element by element, use ifelse(study$mark >= 5, "Pass", "Fail").

Why the order of the ifs matters

R reads the ifs from top to bottom and stops at the first one that is met. With grade(7.5):

ConditionMet with 7.5?What R does
mark >= 9NoMoves on to the next else if
mark >= 7YesReturns "Very good" and looks at nothing else
mark >= 5Never checked
elseNever checked

That is why the conditions go from the most demanding to the least. Look at what happens if the easiest one goes first:

backwards <- function(mark) {
  if (mark >= 5) {
    "Pass"
  } else if (mark >= 9) {
    "Outstanding"
  } else {
    "Fail"
  }
}
backwards(9.5)

Output:

[1] "Pass"

A 9.5 already meets mark >= 5 on the first line, so R returns "Pass" and never gets to ask about the 9. No error, no warning: an outstanding mark comes out as a pass, and you only notice if you look at the result.

And the for from before, one turn at a time:

istudy$student[i]study$mark[i]What cat writesWhy
1Ana7.5Ana -> Very good7.5 does not reach 9, but it does reach 7
2Bea5Bea -> Pass5 does not reach 7, but >= 5 includes the 5
3Carlos6Carlos -> Pass6 does not reach 7, but it does reach 5

The "\n" at the end of the cat is the line break. cat does not add it on its own: without it, the three sentences would come out stuck together on a single line.

Packages: install.packages once, library every time

R comes with all the basic statistics built in, but lots of people have written extra functions and share them in packages. In ME1 you will use some, such as MASS or fitdistrplus, to fit distributions to data. They work in two steps:

  1. Install the package on your computer: install.packages("fitdistrplus"). You do it only once (and again if you upgrade R).
  2. Load it into the session: library(fitdistrplus). You do it in every script that uses it, usually in the first lines.

For example, fitdistr() from the MASS package estimates the mean and standard deviation of a normal distribution from some data:

library(MASS)
marks <- c(7.5, 5, 6, 9, 4, 6.5)
fitdistr(marks, "normal")

Output:

     mean         sd    
  6.3333333   1.6244657 
 (0.6631854) (0.4689429)

The numbers on top are the estimates and those below, in brackets, their standard errors; you will see it calmly in the estimation topic. Notice that the standard deviation it estimates (1.62) is somewhat smaller than sd(marks) (1.78): fitdistr divides by n and not by n − 1.

Writing library(MASS) without ever having installed it (or right after upgrading R). The message is there is no package called ‘MASS’, and it is fixed with an install.packages("MASS"). The opposite happens too: installing the package and forgetting the library(), and then the error is could not find function “fitdistr”.

In the guide Install R and RStudio you have the list of ME1 packages and a script that checks which ones you are missing. In the site’s R playground the library() is enough: the package installs itself the first time.

Try it in the R playground

In the R playground, click the «A data frame from a .csv» pill: it brings a script and a .csv ready to run. Or write this program yourself, which brings together almost the whole article (it needs the study.csv above in the same folder):

dat <- read.csv("study.csv")
dat$group <- factor(dat$group)
dat$passed <- dat$mark >= 5
str(dat)
table(dat$group, dat$passed)
tapply(dat$mark, dat$group, mean)
best <- dat[dat$mark >= 6, c("student", "mark")]
best[order(-best$mark), ]

Output:

'data.frame':	6 obs. of  5 variables:
 $ student: chr  "Ana" "Bea" "Carlos" "Dani" ...
 $ group  : Factor w/ 2 levels "A","B": 1 2 1 2 1 2
 $ hours  : int  10 4 7 12 3 8
 $ mark   : num  7.5 5 6 9 4 6.5
 $ passed : logi  TRUE TRUE TRUE TRUE FALSE TRUE
   
    FALSE TRUE
  A     1    2
  B     0    3
       A        B 
5.833333 6.833333 
  student mark
4    Dani  9.0
1     Ana  7.5
6    Fran  6.5
3  Carlos  6.0

What to watch:

  1. After read.csv, open the Environment tab: dat appears as a data frame of 6 observations and 4 variables. Click it and it opens in the Table tab, like RStudio’s viewer (or type View(dat) in the console below).
  2. In the str output, group is Factor and passed is logi: the two lines before have changed and added columns.
  3. table with two variables gives a contingency table: in group A there is one fail (Eva) and two passes.
  4. The last line sorts with order(). The minus sign reverses the order, so they come out from highest to lowest mark.
  5. Try ?tapply in the console: the Help tab shows R’s documentation, like RStudio’s Help pane.

Summary

StructureWhat it isCreated withQueried with
ListThings of different typeslist()$, [[ ]]
FactorQualitative variablefactor()levels(), table()
Data frameTable: rows are observations, columns are variablesdata.frame(), read.csv()$, [row, col], str()
FunctionA calculation with a namefunction(x) { ... }Calling it: f(x)

Three ideas to keep:

  1. Look at str() whenever you read data. It tells you how many rows and columns there are and what type each one is; if a mark comes out as chr, the problem is in the file, not in your code.
  2. read.csv for commas, read.csv2 for the Spanish CSV. It is the number one mistake in the first lab.
  3. install.packages once, library every time. And if something «does not exist», check capitals and names before anything else.

With this you have the basics to start ME1. If you do not have RStudio yet, the guide Install R and RStudio gets it ready, and How to use RStudio shows you how to find your way around it. In the subject’s first topic, descriptive statistics, you will use everything in this article from the very first line.

Keep goingAll R articles

Did this article help you? Here is how you can support SergioLearns →