0

I've seen a solution for data frames which can definitely be applied in my case (just pop everything into a temporary data frame and do as the solution suggests, but does there exist a method just for vectors?

For example:

x = c('this', 'that', 'here', 'there')
data = c(0.1, 0.2, 0.5, 0.12)
categ = c('cat1', 'cat2', 'cat1', 'cat3')

So after having taken suggestions from comments, this is what I am trying to achieve. Let's take the data I present for example. I want to yield the vectors

cat1 = c(0.1,0.5)
cat2 = c(0.2)
cat3 = c(0.12)

I want the names to be x and the levels to be categ. The way I want to retrieve these vectors is subsetting my data. How do I achieve this?

  • 2
    Your `x` is not actually a `factor` with `levels`. It's a standard `character` vector with an attribute added to it called `"levels"`. It's malformed and doesn't really make sense, hence why `subset` breaks it. If it was a normal `factor`, it would work fine. – thelatemail Mar 20 '19 at 22:40
  • @Ben Bolker I have a set of data that I want to categorize into 3 things. (So break my whole vector into 3 vectors). Then I want to reorder the 3 vectors respectively according to increasing average. Then pop it back into a reordered vector and plot it. – SuperSalami Mar 20 '19 at 22:56
  • 2
    Are you looking for `tapply(data,x,mean)`? (or maybe `tapply(data,names(x),mean)`, or `sort(tapply(data,names(x),mean))`?) It would help a lot if you would give more context -- data you are starting with and your desired output ... – Ben Bolker Mar 20 '19 at 23:26
  • 1
    appreciate the editing effort, but: I think this may be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Please tell us, with a [mcve], what your *ultimate goal* is (show us you sample input and desired output), we'll have a much better chance of helping. – Ben Bolker Mar 20 '19 at 23:39

1 Answers1

0

I'll be honest, I am not sure what you're trying to accomplish. I believe it is something like the following:

x = as.factor(c('this', 'that', 'here', 'there'))
x = factor(x,
           levels = ("0.1", "0.2", "0.5", "0.12"),
           labels = ("cat1", "cat2", "cat3", "cat4")
    )
ThomasPepperz
  • 176
  • 11
  • 1
    respectfully: it's generally better if you can resist (I can't always) to **refrain** from answering questions that aren't clear yet. Answers to unclear questions often just add noise. (Even if you guess right, answering unclear questions passes up an opportunity to encourage the OP to try to clarify ...) – Ben Bolker Mar 20 '19 at 23:48
  • Unfortunately, I have 3 categories in my case, not 4. So ```cat4``` does not exist – SuperSalami Mar 21 '19 at 00:33