How to convert csv list to character vector in R

I am new to R. I have a CSV file with a series of identifiers in a column that looks like this:

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.

+4
source share
2 answers

For a file having only one column file_1.csv , for example:

 F653 F763 F121 F123 

... this is not a CSV file because there are no commas separating the values. However, you can read it with dat1 <- read.csv("file_1.csv",header=F) to get:

 > dat1 V1 1 F653 2 F763 3 F121 4 F123 

Alternatively, a comma-delimited file from two columns of file.csv :

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

... the file can be read as follows:

 > 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 need a vector instead of a data table from file_1.csv , you can get the following:

 > 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 was read as the default factor.

If you need a character vector, you can get this:

 > as.character(dat) [1] "F653" "F763" "F121" "F123" 
+17
source

I want to add another solution. It immediately provides a character vector.

 dat = readLines("file.csv") 
+23
source

Source: https://habr.com/ru/post/1482670/


All Articles