How to save a vector in R as CSV file?


To save a vector in R as CSV file, we can follow the below steps −

  • First of all, create a vector.
  • Then, use write.csv function to save the vector in CSV file.

Example 1

Let’s create a vector as shown below −

 Live Demo

x<-rnorm(20)
x

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

[1] 0.1771119 0.1380003 -0.3802071 -1.1502674 -0.9965625 -0.3693598
[7] -0.5193763 1.4656757 -0.3345711 -0.4971942 -0.3540402 1.3554071
[13] 0.3902927 1.7747777 -2.3264197 -1.3224475 -1.0591576 0.1597807
[19] 3.3330014 -0.1953936

Save the vector in CSV file

Using write.csv file to save the file −

x<-rnorm(20)
write.csv(x,file=”x.csv”,row.names=F)

Output

Example 2

Let’s create a vector as shown below −

 Live Demo

y<-sample(1:50000,20)
y
[1] 41211 37043 14530 17196 41975 28659 9982 42846 12751 37142 20830 32292
[13] 21529 1369 43475 10858 8845 48025 19639 39265

Save the vector in CSV file

Using write.csv file to save the file −

y<-sample(1:50000,20)
write.csv(y,file="y.csv",row.names=F)

Output

Updated on: 14-Aug-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements