teletab
teletab

Reputation: 43

Reading a csv file with string input and convert it to a list

I have string data saved to a csv file.

An example of data is this:

col_name,
TextA TextB,
TextC TextD,

I try to read the csv using read.csv()

When I read the csv I take numeric instead of the string values. I found this because I don't have the values into quotation marks it doesn't recognized them as string.

Is there and way to handle it in order to take a final result like this:

"TextA", "TextB", "TextC", "TextD"

Upvotes: 1

Views: 250

Answers (2)

hvollmeier
hvollmeier

Reputation: 2986

Assuming the file is named test.csv you can import it with:

df <- read.csv('~/Downloads/test.csv',sep=',',header=T,stringsAsFactors = F)

where you set the argument stringsAsFactors to FALSE to import col_name as string. Using strsplit and unlisting the resulting list will give you the elements.

> unlist(strsplit(df[,1],' '))
[1] "TextA" "TextB" "TextC" "TextD"

Upvotes: 2

akrun
akrun

Reputation: 887118

We can directly read it with scan to create a vector

v1 <- sub(",", "", scan("text.csv", sep=" ", what = "", quiet=TRUE)[-1])
v1
#[1] "TextA" "TextB" "TextC" "TextD"

Upvotes: 0

Related Questions