dobiii
dobiii

Reputation: 33

How to convert each row of a column into a list of element?

column

I need every row of this column to be a list. For example, first row to be a list with 1 element, second row with 1 element, third row with 3 element, forth row with 2 elements etc. I need to be able to access each element of these lists. Thank you

I tried everything on the internet but nothing works exactly how I needed to work.

Upvotes: 0

Views: 66

Answers (1)

Josh White
Josh White

Reputation: 1039

Here's an example that will work by splitting each item at each " "

where <- c("Intron", "CDS", "Intron Intron Intron", "Intron Intron", "Not close to gene")
strsplit(where, " ")
[[1]]
[1] "Intron"

[[2]]
[1] "CDS"

[[3]]
[1] "Intron" "Intron" "Intron"

[[4]]
[1] "Intron" "Intron"

[[5]]
[1] "Not"   "close" "to"    "gene" 

EDIT

Example below allows "Not close to gene" and "Not translated" to stay together, and has output as a list of lists (as requested by question)

  • It uses a negative lookup, so that " " followed by "translated", "close", "to", or "gene" won't but split.
  • uses lapply() to apply as.list() to each row
where <- c("Intron", "CDS", "Intron Intron Intron", "Intron Intron", "CDS CDS Not translated Intron",  "Not close to gene")
lapply(
  strsplit(where, " (?!translated|close|to|gene)", perl = TRUE),
  as.list
)
[[1]]
[[1]][[1]]
[1] "Intron"


[[2]]
[[2]][[1]]
[1] "CDS"


[[3]]
[[3]][[1]]
[1] "Intron"

[[3]][[2]]
[1] "Intron"

[[3]][[3]]
[1] "Intron"


[[4]]
[[4]][[1]]
[1] "Intron"

[[4]][[2]]
[1] "Intron"


[[5]]
[[5]][[1]]
[1] "CDS"

[[5]][[2]]
[1] "CDS"

[[5]][[3]]
[1] "Not translated"

[[5]][[4]]
[1] "Intron"


[[6]]
[[6]][[1]]
[1] "Not close to gene"

Upvotes: 1

Related Questions