AngryPanda
AngryPanda

Reputation: 1281

Extract and organise values from a structure

I have the following structure as an output of computation:

structure(c(2L,1L,1L,2L), .Label=c("high","low"), 
    class="factor", prob=c(1,0.667,0.8,0.333))

What is the best way to extract information from this structure and represent in a data frame?

For instance:

Val  Label   Prob
  2   low       1
  1  high   0.667
  1  high     0.8
  2   low   0.333

I have tried as.numeric(), unname() but neither worked.

Upvotes: 2

Views: 35

Answers (1)

Pierre L
Pierre L

Reputation: 28441

We can assign the parts we'd like. And as in most problems there are a few ways to get the attribute:

data.frame(Val=as.integer(x), Label=x, Prob=attr(x,"prob"))
  Val Label  Prob
1   2   low 1.000
2   1  high 0.667
3   1  high 0.800
4   2   low 0.333

Upvotes: 4

Related Questions