0

I'm currently working with some data and really struggle to properly transform it from wide to long data. For reference, this was data in the beginning: data before

Unfortunately, I only learned to do gather () with one key variable, which would produce way to many rows when run several times with different keys, but tried it after looking it up, but it went wrong and I can't find my error. Can someone please help?

I managed to transform it to something close to what I want with the following code:

l <- p %>% gather(column, value, 4:11, 14:25) %>%
  separate (column, into = c("column", "obj_number", "familiarity")) %>%
  spread (column, value) 

l$obj_num = ifelse ((l$obj_number == 'fam') | (l$obj_number == 'nov'), NA, l$obj_number)

Unfortunately, it somehow extracted the names of the objects (car, bear, bus, iguana, seal, wagon) weirdly. I don't know how to make an additional variable out of this. data now

This is a picture of how I imagine my dataframe to look like in the end: data I want

I am wondering what went wrong with my code and if one can run a transformation from wide to long data with multiple variables. simultaneously tried to work from there, but both approaches failed.

Lissy
  • 1
  • 1
  • 1
    Hi Lissy! Welcome to StackOverflow your question is likely to be answered a lot faster if you include the data from your problem, instead of screenshots of the problem (I haven't found a way of converting screenshots into dataframes yet – Mark Jul 19 '23 at 12:15
  • Welcome to SO. Please don't upload code, error messages, results or data as images for [these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557) - and [these](https://xkcd.com/2116/). FYI, `gather` and `spread` have been superceded by `pivot_longer` and `pivot_wider`. – Limey Jul 19 '23 at 12:16
  • 1
    if you could run `dput(p)` and paste the result into your question, that'd be great! – Mark Jul 19 '23 at 12:17

0 Answers0