-1

Here is an example data for reproducibility:

pop     year    type    value
pop3    1980    prev    1.42
pop4    1988    prev    1.53
pop6    1981    prev    1.42
pop8    1980    prev    1.7
pop3    1980    pops    977
pop4    1988    pops    822
pop6    1981    pops    1028
pop8    1980    pops    935

I want to change my data.frame using basic commands from dplyr and tidyr (preferably w/o using df function) into a data.frame that looks like this:

pop     year    prev   pops
pop3    1980    1.42    977
pop4    1988    1.53    822
pop6    1981    1.42    1028
pop8    1980    1.70    935

Any kind of suggestions are welcomed.

pbio
  • 1
  • 2
  • Firstly, you seem to have data as a `data.frame` or `tibble` not as a `matrix`. Secondly, there is no `df` package, so I'm not sure what you mean by *"preferably w/o using df package"*. Lastly, this seems to have nothing to do with transposing data. Can you clarify why/how you want to transpose your data? This looks like a simple long to wide reshape to me. – Maurits Evers Sep 25 '18 at 22:56
  • Hi, thank you for this warm welcome Maurits. Yes it is a tibble. I meant to say data.frame function. I recently started learning R, so it’s hard to obtain fluency in days. I meant transpose; switching rows to columns, columns to rows. But if it seems to be not working. That’s fine. – pbio Sep 26 '18 at 02:56
  • Ok, I didn't mean to sound harsh, but please understand that Stack Overflow works best if you help yourself first. That means for example using the search function to find similar questions. Reshaping data from wide to long (and the reverse) is one of the most frequently asked question around here, with multiple posts a day on that topic. Furthermore, just like with any coding language, it is important to use precise terminology. A `data.frame` is different from a `matrix`. Transposition is different from reshaping. And so on. We can't help if we don't understand what you want to do. – Maurits Evers Sep 26 '18 at 03:25

1 Answers1

1

We can use spread from tidyr

> df1 %>% spread(indicator, value)
    pop year popsize prevalence
1 pop3B 1980     977   1.422822
2 pop4A 1988     822   1.532217
3 pop6B 1981    1028   1.416042
4 pop8B 1980     935   1.700781
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138