生信學(xué)習(xí)基礎(chǔ)_R語言04_data-wrangling: Subsetting Vectors and Factors數(shù)據(jù)整理-取向量和因子的子集

原文地址:https://hbctraining.github.io/Intro-to-R/lessons/04_introR-data-wrangling.html

大神的中文整理版:http://m.itdecent.cn/p/d1365c9f8422

本文是我拷貝的原文,加了自己的筆記和練習(xí)題答案。

Learning Objectives

  • Construct data structures to store external data in R.
  • Inspect data structures in R.
  • Demonstrate how to subset data from data structures.

Reading data into R

Regardless of the specific analysis in R we are performing, we usually need to bring data in for the analysis. The function in R we use will depend on the type of data file we are bringing in (e.g. text, Stata, SPSS, SAS, Excel, etc.) and how the data in that file are separated, or delimited. The table below lists functions that can be used to import data from common file formats.

Data type Extension Function Package
Comma separated values csv read.csv() utils (default)
read_csv() readr (tidyverse)
Tab separated values tsv read_tsv() readr
Other delimited formats txt read.table() utils
read_table() readr
read_delim() readr
Stata version 13-14 dta readdta() haven
Stata version 7-12 dta read.dta() foreign
SPSS sav read.spss() foreign
SAS sas7bdat read.sas7bdat() sas7bdat
Excel xlsx, xls read_excel() readxl (tidyverse)

For example, if we have text file separated by commas (comma-separated values), we could use the function read.csv. However, if the data are separated by a different delimiter in a text file, we could use the generic read.table function and specify the delimiter as an argument in the function.

When working with genomic data, we often have a metadata file containing information on each sample in our dataset. Let’s bring in the metadata file using the read.csv function. Check the arguments for the function to get an idea of the function options:

?read.csv

The read.csv function has one required argument and several options that can be specified. The mandatory argument is a path to the file and filename, which in our case is data/mouse_exp_design.csv. We will put the function to the right of the assignment operator, meaning that any output will be saved as the variable name provided on the left.

metadata <- read.csv(file="data/mouse_exp_design.csv")

Note: By default, read.csv converts (= coerces) columns that contain characters (i.e., text) into the factor data type. Depending on what you want to do with the data, you may want to keep these columns as character. To do so, read.csv() and read.table() have an argument called stringsAsFactors which can be set to FALSE.

Inspecting data structures

There are a wide selection of base functions in R that are useful for inspecting your data and summarizing it. Let’s use the metadata file that we created to test out data inspection functions.

Take a look at the dataframe by typing out the variable name metadata and pressing return; the variable contains information describing the samples in our study. Each row holds information for a single sample, and the columns contain categorical information about the sample genotype(WT or KO), celltype (typeA or typeB), and replicate number (1,2, or 3).

metadata

          genotype celltype replicate
sample1        Wt    typeA      1
sample2        Wt    typeA      2
sample3        Wt    typeA      3
sample4        KO    typeA      1
sample5        KO    typeA      2
sample6        KO    typeA      3
sample7        Wt    typeB      1
sample8        Wt    typeB      2
sample9        Wt    typeB      3
sample10       KO    typeB      1
sample11       KO    typeB      2
sample12       KO    typeB      3

Suppose we had a larger file, we might not want to display all the contents in the console. Instead we could check the top (the first 6 lines) of this data.frame using the function head():

head(metadata)

Previously, we had mentioned that character values get converted to factors by default using data.frame. One way to assess this change would be to use the __str__ucture function. You will get specific details on each column:

str(metadata)

'data.frame':   12 obs. of  3 variables:
 $ genotype : Factor w/ 2 levels "KO","Wt": 2 2 2 1 1 1 2 2 2 1 ...
 $ celltype : Factor w/ 2 levels "typeA","typeB": 1 1 1 1 1 1 2 2 2 2 ...
 $ replicate: num  1 2 3 1 2 3 1 2 3 1 ...

As you can see, the columns genotype and celltype are of the factor class, whereas the replicate column has been interpreted as integer data type.

You can also get this information from the “Environment” tab in RStudio.

List of functions for data inspection

We already saw how the functions head() and str() can be useful to check the content and the structure of a data.frame. Here is a non-exhaustive list of functions to get a sense of the content/structure of data.

  • All data structures - content display:
    • str(): compact display of data contents (env.)
    • class(): data type (e.g. character, numeric, etc.) of vectors and data structure of dataframes, matrices, and lists.
    • summary(): detailed display, including descriptive statistics, frequencies
    • head(): will print the beginning entries for the variable
    • tail(): will print the end entries for the variable
  • Vector and factor variables:
    • length(): returns the number of elements in the vector or factor
  • Dataframe and matrix variables:
    • dim(): returns dimensions of the dataset
    • nrow(): returns the number of rows in the dataset
    • ncol(): returns the number of columns in the dataset
    • rownames(): returns the row names in the dataset
    • colnames(): returns the column names in the dataset

Selecting data using indices and sequences

When analyzing data, we often want to partition the data so that we are only working with selected columns or rows. A data frame or data matrix is simply a collection of vectors combined together. So let’s begin with vectors and how to access different elements, and then extend those concepts to dataframes.

Vectors

Selecting using indices

If we want to extract one or several values from a vector, we must provide one or several indices using square brackets [ ] syntax. The index represents the element number within a vector (or the compartment number, if you think of the bucket analogy). R indices start at 1. Programming languages like Fortran, MATLAB, and R start counting at 1, because that’s what human beings typically do. Languages in the C family (including C++, Java, Perl, and Python) count from 0 because that’s simpler for computers to do.

Let’s start by creating a vector called age:

age <- c(15, 22, 45, 52, 73, 81)

vector indices

Suppose we only wanted the fifth value of this vector, we would use the following syntax:

age[5]

If we wanted all values except the fifth value of this vector, we would use the following:

age[-5]

If we wanted to select more than one element we would still use the square bracket syntax, but rather than using a single value we would pass in a vector of several index values:

idx <- c(3,5,6) # create vector of the elements of interest
age[idx]

To select a sequence of continuous values from a vector, we would use : which is a special function that creates numeric vectors of integer in increasing or decreasing order. Let’s select the first four values from age:

age[1:4]

Alternatively, if you wanted the reverse could try 4:1 for instance, and see what is returned.


Exercises

  1. Create a vector called alphabets with the following letters, C, D, X, L, F.
  2. Use the associated indices along with [ ] to do the following:
    • only display C, D and F
    • display all except X
    • display the letters in the opposite order (F, L, X, D, C)

alphabets <- c('C','D','X','L','F')
y <- c(1,2,5)
alphabets[y]
alphabets[-3]
alphabets[5:1]

Selecting using indices with logical operators

We can also use indices with logical operators. Logical operators include greater than (>), less than (<), and equal to (==). A full list of logical operators in R is displayed below:

Operator description

We can use logical expressions to determine whether a particular condition is true or false. For example, let’s use our age vector:

age

If we wanted to know if each element in our age vector is greater than 50, we could write the following expression:

age > 50

Returned is a vector of logical values the same length as age with TRUE and FALSE values indicating whether each element in the vector is greater than 50.

[1] FALSE FALSE FALSE  TRUE  TRUE  TRUE

We can use these logical vectors to select only the elements in a vector with TRUE values at the same position or index as in the logical vector.

Create an index with logical operators to select all values in the age vector over 50 or age less than 18:

idx <- age > 50 | age < 18

idx

age

age[idx]

Indexing with logical operators using the which() function

While logical expressions will return a vector of TRUE and FALSE values of the same length, we could use the which() function to output the indices where the values are TRUE. Indexing with either method generates the same results, and personal preference determines which method you choose to use. For example:

idx <- which(age > 50 | age < 18)

idx

age[idx]

Notice that we get the same results regardless of whether or not we use the which(). Also note that while which() works the same as the logical expressions for indexing, it can be used for multiple other operations, where it is not interchangeable with logical expressions.

Note about Nesting functions:

Instead of creating the idx object in the above sections, we could have just place the logical operations and/or functions within the brackets.

age[which(age > 50 | age < 18)] is identical to age[idx] above.

Factors

Since factors are special vectors, the same rules for selecting values using indices apply. The elements of the expression factor created previously had the following categories or levels: low, medium, and high.

Let’s extract the values of the factor with high expression, and let’s using nesting here:

expression[expression == "high"]    ## This will only return those elements in the factor equal to "high"

Nesting note:

The piece of code above was more efficient with nesting; we used a single step instead of two steps as shown below:

Step1 (no nesting): idx <- expression == "high"

Step2 (no nesting): expression[idx]


Exercise

Extract only those elements in samplegroup that are not KO (nesting the logical operation is optional).

samplegroup
samplegroup[samplegroup!= "KO"]

Releveling factors

We have briefly talked about factors, but this data type only becomes more intuitive once you’ve had a chance to work with it. Let’s take a slight detour and learn about how to relevel categories within a factor.

To view the integer assignments under the hood you can use str():

expression

str(expression)
Factor w/ 3 levels "high","low","medium": 2 1 3 1 2 3 1

The categories are referred to as “factor levels”. As we learned earlier, the levels in the expressionfactor were assigned integers alphabetically, with high=1, low=2, medium=3. However, it makes more sense for us if low=1, medium=2 and high=3, i.e. it makes sense for us to “relevel” the categories in this factor.

To relevel the categories, you can add the levels argument to the factor() function, and give it a vector with the categories listed in the required order:

expression <- factor(expression, levels=c("low", "medium", "high"))     # you can re-factor a factor 

str(expression)
Factor w/ 3 levels "low","medium",..: 1 3 2 3 1 2 3

Now we have a releveled factor with low as the lowest or first category, medium as the second and high as the third. This is reflected in the way they are listed in the output of str(), as well as in the numbering of which category is where in the factor.

Note: Releveling becomes necessary when you need a specific category in a factor to be the “base” category, i.e. category that is equal to 1. One example would be if you need the “control” to be the “base” in a given RNA-seq experiment.


Exercise

Use the samplegroup factor we created in a previous lesson, and relevel it such that KO is the first level followed by CTL and OE.

samplegroup
samplegroup <- factor(samplegroup,levels = c("KO","CTL","OE"))
str(samplegroup)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文轉(zhuǎn)載自知乎 作者:季子烏 筆記版權(quán)歸筆記作者所有 其中英文語句取自:英語流利說-懂你英語 ——————————...
    Danny_Edward閱讀 44,098評(píng)論 4 38
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,941評(píng)論 0 13
  • 今天凌晨1點(diǎn)多才睡,第一次醒來被自己設(shè)置的7點(diǎn)22分的鬧鐘給弄醒了,也沒事,不過心里模模糊糊告訴自己,一醒來那得寫...
    自然與大象吧閱讀 244評(píng)論 0 1
  • 這一點(diǎn),在當(dāng)時(shí)肯定是不存在的,畢竟還是小屁孩一枚,能懂多少這概念,又知道什么好與不好,什么未來與現(xiàn)在~ 現(xiàn)在談這個(gè)...
    如果你想和我一樣閱讀 330評(píng)論 0 0
  • 今天學(xué)習(xí)了Python的歸并排序。歸并排序算法是一個(gè)穩(wěn)定的算法,所謂穩(wěn)定的意思就是列表中相同元素的先后順序在排序前...
    422d602c244f閱讀 246評(píng)論 0 1

友情鏈接更多精彩內(nèi)容