Importing .csv files

Importing .csv files

Introduction

Working with data provided by R packages is a great way to learn data science tools, but you want to apply what you’ve learned to your own data at some point. In this section, you’ll learn the basics of reading data files into R.

R uses object-oriented language (aka object-based programming): R code builds “chains” of objects and functions to execute tasks.

  • Objects are holders of information, like a single value, word, data table, graph, etc.. Objects are in between the brackets.

  • Functions are special objects with a job. Functions require objects (e.g. data, parameters, etc.) to perform their tasks. Functions are before the brackets.

What can R read?

  • R does not read spaces. You can add spaces in you code for readability.

  • Keep object names short and informative. You can use “_” and “.” as well as numbers

  • you cannot use special symbols (%,&,*,#,!), “,”, nor can you start an object name with a number.

NOTE: If you repeat a file name in your workspace, the old file will be overwritten without a warning prompt. Keep track of your file names, so you know which files to use.

Loading data

In this chapter, you’ll learn how to load flat files in R with the readr package, which is part of the core tidyverse.

  • First, create a new Project, named Cell425 (or whatever you prefer)

  • Next create a new R Markdown file. File > New File > R Markdown

If you have not already done so, set your R working directory:

setwd (".") 
  • Download the cellstocks file and cellstocksold file from the shared drive, and place them in your working directory

Next, activate tidyverse

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

You can also check the box in front in the panel at the left bottom (unless you changed the layout), make sure you select the Packages Tab.

We can read the test files into R using read.csv().

cellstocks <- read.csv("cellstocks.csv")
cellstocksold <- read.csv("cellstocksold.csv")

The cellstocksold and cellstocks file should now appear in the ‘environment’ in the top right panel. You can access them in the markdown or console pane by using this code:

cellstocks
     Cell.culture.N2.stocks          X                    X.1   X.2 X.3  X.4
1        Updated Jan 6 2026                                                 
2  Storage location MSB5-12                                                 
3                   Dewar 2                                                 
4                 racks 1-8                                                 
5                  SampleID   CellLine                 Origin vials  DT rack
6                         1       HeLa                  Human     4  24    1
7                         2     HEK293                  Human     5  30    1
8                         3       A549                  Human     7  24    1
9                         4      MCF-7                  Human   N/A  40    1
10                        5 MDA-MB-231                  Human     5  34    1
11                        6      HepG2                  Human     6  60    1
12                        7     Caco-2                  Human    12  40    1
13                        8      HT-29                  Human    24  30    1
14                        9     HCT116                  Human     1  22    1
15                       10       PC-3                  Human     2  40    1
16                       11      LNCaP                  Human     6        2
17                       12    U-87 MG                  Human     8  36    2
18                       13    SH-SY5Y                  Human    94  70    2
19                       14       U2OS                  Human     6  32    2
20                       15       A431                  Human     2  36    2
21                       16     PANC-1                  Human     7  28    2
22                       17    SK-OV-3                  Human     8  40    2
23                       18      DU145                  Human     2        2
24                       19     Jurkat                  Human     4  26    2
25                       20       K562                  Human     7  30    3
26                       21      THP-1                  Human     9  45    3
27                       22      HL-60                  Human   N/A  36    3
28                       23       Raji                  Human        24    3
29                       24       U937                  Human        32    3
30                       25      Daudi                  Human        36    3
31                       26    NIH/3T3                  Mouse     6  26    3
32                       27        CHO        Chinese Hamster        24    3
33                       28       Vero   African Green Monkey     0  30    3
34                       29      COS-7   African Green Monkey     1  48    3
35                       30       MDCK                    Dog     3  24    4
36                       31     BHK-21           Baby Hamster    10  18    4
37                       32  RAW 264.7                  Mouse     6  15    4
38                       33   MC3T3-E1                  Mouse     6  36    4
39                       34      C2C12                  Mouse     5  20    4
40                       35     3T3-L1                  Mouse     2  24    4
41                       36       PC12                    Rat     8  48    5
42                       37      HaCaT                  Human     7  30    5
43                       38      HUVEC                  Human     4  36    5
44                       39        Sf9 Insect (S. frugiperda)     3  30    5
45                       40  High Five         Insect (T. ni)    10  24    5
                                    X.5
1                                      
2                                      
3                                      
4                                      
5                    Cell Type / Source
6               Cervical adenocarcinoma
7                      Embryonic kidney
8     Lung carcinoma (alveolar type II)
9        Breast adenocarcinoma ($ER^+$)
10        Triple-negative breast cancer
11             Hepatocellular carcinoma
12            Colorectal adenocarcinoma
13            Colorectal adenocarcinoma
14                 Colorectal carcinoma
15 Prostate adenocarcinoma (metastatic)
16              Prostate adenocarcinoma
17              Glioblastoma multiforme
18                        Neuroblastoma
19                         Osteosarcoma
20                 Epidermoid carcinoma
21     Pancreatic ductal adenocarcinoma
22               Ovarian adenocarcinoma
23                   Prostate carcinoma
24                T-lymphocyte leukemia
25   Chronic myelogenous leukemia (CML)
26             Acute monocytic leukemia
27               Promyelocytic leukemia
28      Burkitt's lymphoma B-lymphocyte
29                 Histiocytic lymphoma
30     Burkitt's lymphoma B-lymphoblast
31                 Embryonic fibroblast
32                     Ovary epithelial
33                    Kidney epithelial
34        Kidney fibroblast-like (SV40)
35                    Kidney epithelial
36                    Kidney fibroblast
37                  Monocyte/macrophage
38                       Pre-osteoblast
39                             Myoblast
40                        Pre-adipocyte
41                     Pheochromocytoma
42            Immortalized keratinocyte
43     Umbilical vein endothelial cells
44                        Ovarian cells
45                        Ovarian cells

You can also click on the file in the panel on the right to see what it contains. This will open a new tab. Close it after viewing.

You can list the files in the workspace by using the ls() function.

ls()
[1] "cellstocks"    "cellstocksold"

You can remove files from the workspace with the rm() function

rm("cellstocksold")

The file is not active anymore in your workspace, but it is still in your working directory.

when you look at the cellstocks file, there are some issues with it.

  • There is metadata in the first 5 rows of the data table. You need to tell R to skip rows 1-5 and start on row 6

  • The data set has a header row of columns names (header argument). R will default to assume that there are no column names (e.g. FALSE) so it adds its own unless you specify the columns are already named.

  • Blank cells (” “) in the dataset represent NA values ( the na.strings argument), but in this case N/A and NA are also blank values. We can indicate blanks with the na = c() function.

The resulting import function is the following:

data1 <- read.csv("cellstocks.csv", header=T, skip=5, na = c("N/A", "NA", ""))
data1
   SampleID   CellLine                 Origin vials DT rack
1         1       HeLa                  Human     4 24    1
2         2     HEK293                  Human     5 30    1
3         3       A549                  Human     7 24    1
4         4      MCF-7                  Human    NA 40    1
5         5 MDA-MB-231                  Human     5 34    1
6         6      HepG2                  Human     6 60    1
7         7     Caco-2                  Human    12 40    1
8         8      HT-29                  Human    24 30    1
9         9     HCT116                  Human     1 22    1
10       10       PC-3                  Human     2 40    1
11       11      LNCaP                  Human     6 NA    2
12       12    U-87 MG                  Human     8 36    2
13       13    SH-SY5Y                  Human    94 70    2
14       14       U2OS                  Human     6 32    2
15       15       A431                  Human     2 36    2
16       16     PANC-1                  Human     7 28    2
17       17    SK-OV-3                  Human     8 40    2
18       18      DU145                  Human     2 NA    2
19       19     Jurkat                  Human     4 26    2
20       20       K562                  Human     7 30    3
21       21      THP-1                  Human     9 45    3
22       22      HL-60                  Human    NA 36    3
23       23       Raji                  Human    NA 24    3
24       24       U937                  Human    NA 32    3
25       25      Daudi                  Human    NA 36    3
26       26    NIH/3T3                  Mouse     6 26    3
27       27        CHO        Chinese Hamster    NA 24    3
28       28       Vero   African Green Monkey     0 30    3
29       29      COS-7   African Green Monkey     1 48    3
30       30       MDCK                    Dog     3 24    4
31       31     BHK-21           Baby Hamster    10 18    4
32       32  RAW 264.7                  Mouse     6 15    4
33       33   MC3T3-E1                  Mouse     6 36    4
34       34      C2C12                  Mouse     5 20    4
35       35     3T3-L1                  Mouse     2 24    4
36       36       PC12                    Rat     8 48    5
37       37      HaCaT                  Human     7 30    5
38       38      HUVEC                  Human     4 36    5
39       39        Sf9 Insect (S. frugiperda)     3 30    5
40       40  High Five         Insect (T. ni)    10 24    5
                     Cell.Type...Source
1               Cervical adenocarcinoma
2                      Embryonic kidney
3     Lung carcinoma (alveolar type II)
4        Breast adenocarcinoma ($ER^+$)
5         Triple-negative breast cancer
6              Hepatocellular carcinoma
7             Colorectal adenocarcinoma
8             Colorectal adenocarcinoma
9                  Colorectal carcinoma
10 Prostate adenocarcinoma (metastatic)
11              Prostate adenocarcinoma
12              Glioblastoma multiforme
13                        Neuroblastoma
14                         Osteosarcoma
15                 Epidermoid carcinoma
16     Pancreatic ductal adenocarcinoma
17               Ovarian adenocarcinoma
18                   Prostate carcinoma
19                T-lymphocyte leukemia
20   Chronic myelogenous leukemia (CML)
21             Acute monocytic leukemia
22               Promyelocytic leukemia
23      Burkitt's lymphoma B-lymphocyte
24                 Histiocytic lymphoma
25     Burkitt's lymphoma B-lymphoblast
26                 Embryonic fibroblast
27                     Ovary epithelial
28                    Kidney epithelial
29        Kidney fibroblast-like (SV40)
30                    Kidney epithelial
31                    Kidney fibroblast
32                  Monocyte/macrophage
33                       Pre-osteoblast
34                             Myoblast
35                        Pre-adipocyte
36                     Pheochromocytoma
37            Immortalized keratinocyte
38     Umbilical vein endothelial cells
39                        Ovarian cells
40                        Ovarian cells

The metadata are removed, R recognizes the header and it should now say NA, instead of N/A. R can read the latter as a missing value, instead of the text N/A. This function is very useful when you work with large matrices; you will almost always have missing values.

Other ways to check the file structure are:

head(data1) – shows the top 6 rows
tail(data1) - shows the bottom 6 rows

Exporting data

To save the edited file to the working directory (or elsewhere is you define the path) you use:

write.csv(DataName, “FileName”, row.names=F)

DataName refers to the name of the data in the workspace
FileName refers to the name you want the saved file to have in the wd
row.names=F means R will not add and additional row number, before sample_ID

write.csv(data1, "cellstocksnew.csv", row.names=F)

The file should now appear in your working directory.