Low Yi Xiang
Low Yi Xiang

Reputation: 757

Extracting out numbers in a list from R

I am reading this from a CSV file, and i need to write a function that churns out a final data frame, so given a particular entry, i have

x [1] {2,4,5,11,12}

139 Levels: {1,2,3,4,5,6,7,12,17} ...

i can change it to x2<-as.character(x)

which gives me

x [1] "{2,4,5,11,12}"

how do i extract 2,4,5,11,12 out? (having 5 elements)

i have tried to use various ways, like gsub, but to no avail

can anyone please help me?

Upvotes: 0

Views: 864

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57686

It sounds like you're trying to import a database table that contains arrays. Since R doesn't know about such data structures, it treats them as text.

Try this. I assume the column in question is x. The result will be a list, with each element being the vector of array values for that row in the table.

dat <- read.csv("<file>", stringsAsFactors=FALSE)
dat$x <- strsplit(gsub("\\{(.*)\\}", "\\1", dat$x), ",")

Upvotes: 2

Related Questions