EricC
EricC

Reputation: 15

R how to extract specific elements in a data frame consisting of character lists

I have a data frame labels consisting of 3 rows of 1 column like this:

 labels
                  labels(n)
 1 Text, Commission20120125
 2    Text, Council2015mmdd
 3 Text, Parliament20140312

with:

 labels[1,]
 [[1]]
 [1] "Text"               "Commission20120125"

and:

  labels[2,]
  [[1]]
 [1] "Text"            "Council2015mmdd"

and:

 labels[3,]
 [[1]]
 [1] "Text"               "Parliament20140312"

Is there any "simple" way to access everything but "Text" and put it in a vector, like this:

c("Commission20120125", "Council2015mmdd", "Parliament20140312")

As my only solution so far is to manually do:

l1 <- as.vector(labels[1,])  
l1 <- unlist(l1)  
l1 <- str_extract(l1, "[A-Z][a-z]+[0-9]+")
l <- l1[2]

and so on for every raw.

Upvotes: 0

Views: 87

Answers (2)

agstudy
agstudy

Reputation: 121578

Another option (I think it is faster),

unlist(labels)[c(FALSE,TRUE)] ## use of recycling here 

      labelsn2             labelsn4             labelsn6 
"Commission20120125"    "Council2015mmdd" "Parliament20140312" 

Upvotes: 1

akrun
akrun

Reputation: 887193

You may try

sapply(labels[,1], '[',2)
#[1] "Commission20120125" "Council2015mmdd"    "Parliament20140312"

data

labels <- data.frame(labelsn = I(list(c('Text', 'Commission20120125'),
 c('Text', 'Council2015mmdd'), c('Text', 'Parliament20140312'))))

Upvotes: 1

Related Questions