Categories

Nov 4, 2019 in R Language

Q:

R Data Frame: Create, Append, Select, Subset

1 Answer

Nov 4, 2019

data frame is a list of vectors which are of equal length. A matrix contains only one type of data, while a data frame accepts different data types (numeric, character, factor, etc.).

We can create a data frame by passing the variable a,b,c,d into the data.frame() function. We can name the columns with name() and simply specify the name of the variables.

data.frame(df, stringsAsFactors = TRUE)

Arguments:

  • df: It can be a matrix to convert as a data frame or a collection of variables to join
  • stringsAsFactors: Convert string to factor by default
  • Slice Data Frame

    It is possible to SLICE values of a Data Frame. We select the rows and columns to return into bracket precede by the name of the data frame.

    A data frame is composed of rows and columns, df[A, B]. A represents the rows and B the columns. We can slice either by specifying the rows and/or columns.

    From picture 1, the left part represents the rows, and the right part is the columns. Note that the symbol : means to. For instance, 1:3 intends to select values from 1 to 3.

Append a Column to Data Frame

You can also append a column to a Data Frame. You need to use the symbol $ to append a new variable.

Select a Column of a Data Frame

Sometimes, we need to store a column of a data frame for future use or perform operation on a column. We can use the $ sign to select the column from a data frame.

# Select the column ID
df$ID

Subset a Data Frame

In the previous section, we selected an entire column without condition. It is possible to subset based on whether or not a certain condition was true.

We use the subset() function.

subset(x, condition)
arguments:
- x: data frame used to perform the subset
- condition: define the conditional statement
Click here to read more about Loan/Mortgage
Click here to read more about Insurance

Related questions

Madanswer
Jul 28, 2019 in R Language
Nov 6, 2019 in R Language
Jul 28, 2019 in R Language
...