How to Manually Enter Raw Data in R?
In this article, we will discuss how to manually enter raw data in the R Programming Language.
In the R Language, we work with loads of different datasets by importing them through a variety of file formats. But Sometimes we need to enter our own raw data in the form of a character vector, a data frame, or a matrix. There are multiple methods to enter the raw data manually in the R Language.
Enter data as a vector
To enter data as a vector in the R Language, we use the combine function i.e. c(). The c() function is a generic function that combines its arguments to form a vector. All arguments are coerced to a common type. To create a numeric vector we pass numbers as arguments to the c() function. To create a character vector we pass the strings or characters as arguments to the c() function.
Syntax: sample_vector <- c( data1, data2, ….. , datan )
where: data1, data2…: determines the numeric values that comprise the vector.
Example: Demonstrating basic character and numeric vectors.
Character vector: "geeks" "for" "geeks" Class: "character" Numeric vector: 1 2 3 4 5 Class: "numeric"
Enter data as a data frame
To enter data as a data frame in the R Language, we use the data.frame() function. The data.frame() function creates data frames that are tightly coupled collections of variables. These data frames are widely used as the fundamental data structure in the R Language. A single data frame can contain different vectors of different classes together thus it becomes one data structure for all the needs.
data_frame <- data.frame( column_name1 = vector1, column_name2 = vector2 )
- column_name1, column_name2: determines the name for columns in data frame
- vector1, vector2: determines the data vector that contain data values for data frame columns.
Example: Basic data frame that contains one numeric vector and one character vector.
Data Frame: id name 1 1 geeks 2 2 for 3 3 geeks Class: "data.frame" Summary: id name Min. :1.0 Length:3 1st Qu.:1.5 Class :character Median :2.0 Mode :character Mean :2.0 3rd Qu.:2.5 Max. :3.0
Enter data as a matrix
To enter data as a matrix in the R Language, we create all the columns of the matrix as a vector and then use the column binding function that is cbind() to merge them together into a matrix. The cbind() function is a merge function that combines two data frames or vectors with the same number of rows into a single data frame.
Syntax: mat <- cbind( col1, col2 )
where, col1, col2: determines the column vectors that are to be merged to form a matrix.
Here, is a basic 3X3 matrix in the R Language made using the cbind() function.
Matrix: col1 col2 col3 [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 Class: "matrix" "array" Summary: col1 col2 col3 Min. :1.0 Min. :4.0 Min. :7.0 1st Qu.:1.5 1st Qu.:4.5 1st Qu.:7.5 Median :2.0 Median :5.0 Median :8.0 Mean :2.0 Mean :5.0 Mean :8.0 3rd Qu.:2.5 3rd Qu.:5.5 3rd Qu.:8.5 Max. :3.0 Max. :6.0 Max. :9.0