Here we are explaining how to write an R program to convert a given data frame to a list by rows. Here we are using a built-in function data.frame(). A data frame is used for storing data tables which has a list of vectors with equal length. The data frames are created by function data.frame(), which has tightly coupled collections of variables. The syntax of this function is,
data.frame(…, row.names = NULL, check.rows = FALSE,check.names = TRUE, fix.empty.names = TRUE,stringsAsFactors = default.stringsAsFactors())
Where dots(...) indicates the arguments are of either the form value or tag = value and row. name is a NULL or a single integer or character string.
Below are the steps used in the R program to convert a given data frame to a list by rows. In this R program, we directly give the data frame to a built-in function. Here we are using variables E, N, S, A, Q for holding different types of vectors. Call the function data.frame() for creating data frame. Finally, Convert the data frame into list L by calling split(E, seq(nrow(E))). Here split() helps to divide the vector or data frame containing values into groups. And seq() method helps to generate regular sequences.
STEP 1: Assign variables E,N,S,A,Q with vector values
STEP 2: Create a data frame E with given values
STEP 3: Print the data frame
STEP 4: Convert the data frame into list L by calling split(E, seq(nrow(E)))
STEP 5: Print the new list L
E = data.frame(
N = c('Jhon', 'Hialy', 'Albert', 'James', 'Delma'),
S = c(10, 9.5, 12.2, 11, 8),
A = c(2, 1, 2, 4, 1),
Q = c('yes', 'no', 'yes', 'no', 'no')
)
print("Original dataframe:")
print(E)
L = split(E, seq(nrow(E)))
print("dataframe rows to a list:")
print(L)
[1] "Original dataframe:" N S A Q 1 Jhon 10.0 2 yes 2 Hialy 9.5 1 no 3 Albert 12.2 2 yes 4 James 11.0 4 no 5 Delma 8.0 1 no [1] "dataframe rows to a list:" $`1` N S A Q 1 Jhon 10 2 yes $`2` N S A Q 2 Hialy 9.5 1 no $`3` N S A Q 3 Albert 12.2 2 yes $`4` N S A Q 4 James 11 4 no $`5` N S A Q 5 Delma 8 1 no