Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a csv list to a character vector in R

Tags:

r

I am new to R. I have a .csv file with a series of identifiers in a column that look like:

F653
F763
F121
F123
...

These values are in a vertical column, and I want to import them into R in the format

data <- c("F653", "F763", "F121", "F123")

I'm sure this is relatively easy but I'm stuck, so any advice would help.

like image 732
user2419293 Avatar asked May 25 '13 00:05

user2419293


People also ask

How do I import a csv dataset into RStudio?

In RStudio, click on the Workspace tab, and then on “Import Dataset” -> “From text file”. A file browser will open up, locate the . csv file and click Open. You'll see a dialog that gives you a few options on the import.

How do I convert a CSV file to a matrix in python?

Line 1: We import the NumPy library. Line 3-4: We open the sampleCSV file and we pass both CSVData and the delimiter to NumPy np. genfromtxt () function, which returns the data into a 2D array. Line 6: We finally print the result which shows that now our CSV data converted into a 2D array.


2 Answers

Given a file that only has one column file_1.csv, e.g.:

F653
F763
F121
F123

... it isn't really a CSV file because there are no commas separating the values. Nevertheless, you can read it with dat1 <- read.csv("file_1.csv",header=F) to obtain:

> dat1
    V1
1 F653
2 F763
3 F121
4 F123

Alternatively, a two-column comma-separated file file.csv:

F653,1
F763,2
F121,3
F123,4

... the file can be read in like:

> dat <- read.csv("file.csv",header=F)
> dat
    V1 V2
1 F653  1
2 F763  2
3 F121  3
4 F123  4

However, dat and dat1 are both data tables. If you want a vector instead of a data table from file_1.csv, you can get that like this:

> dat <- read.csv("file.csv",header=F)$V1
> dat
[1] F653 F763 F121 F123
Levels: F121 F123 F653 F763

You can see that the vector has been read as a factor by default.

If you want a character vector, you can get that from:

> as.character(dat)
[1] "F653" "F763" "F121" "F123"
like image 89
Simon Avatar answered Oct 30 '22 14:10

Simon


I'd like to add another solution. It provides a character vector right away.

dat = readLines("file.csv")
like image 32
Andrey Shabalin Avatar answered Oct 30 '22 16:10

Andrey Shabalin