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.
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.
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.
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"
I'd like to add another solution. It provides a character vector right away.
dat = readLines("file.csv")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With