Open In App

How to convert CSV into array in R?

In this article, we are going to see how to convert CSV into an array in R Programming Language. If we load this file into any environment like python, R language .etc, the data will be displayed in rows and columns format, let us convert CSV file into an array. Each and every column in the CSV will be converted into array of multiple dimensions.

Method 1 : Using loop.



Here we will use loop to convert all the columns in to the array. 




setwd("C:/Users/KRISHNA KARTHIKEYA/Documents")
 
df = read.csv("item.csv"
lst1 = list() 
for(i in 1:ncol(df)) {     
  lst1[[i]] <- df[ , i]   
}
 
names(lst1) = colnames(df) 
arr = array(unlist(lst1),
            dim = c(5, 5, 3))
print(arr)

Output:



Explanation :

Method 2: Extract every column into separate variable and pass to array() function.




setwd('C:/Users/KRISHNA KARTHIKEYA/Documents')
 
df = read.csv('item.csv')
a = df$id
b = df$item
c = df$quantity
d = df$price
e = df$bought
f = df$forenoon
g = df$afternoon
arr = array(c(a, b, c, d, e, f, g),
            dim = c(5, 3 ,2))
print(arr)

Output:

Explanation :


Article Tags :