0

I wanted to create a new table OR dataframe from an existing dataframe.

My original dataframe looks like the below:

fruit col1 col2 col3
apple 1 3 2
banana 4 7 3
lime 8 10 5
orange 2 6 8
grape 7 5 10

I would like it to look like this:

id fruit
1 apple
2 apple
2 apple
3 apple
3 banana
4 banana
5 lime
5 grape
... ...

I know how to rename columns so renaming to id is fine. I just don't know how to pull the data from the dataframe to create a new table as I am fairly new to R.

Any help would be appreciated!

1 Answer 1

0
library(tidyverse)

read_table("fruit   col1    col2    col3
apple   1   3   2
banana  4   7   3
lime    8   10  5
orange  2   6   8
grape   7   5   10") %>% 
  pivot_longer(-fruit, 
               values_to = "id") %>%  
  select(id, fruit)

# A tibble: 15 × 2
      id fruit 
   <dbl> <chr> 
 1     1 apple 
 2     3 apple 
 3     2 apple 
 4     4 banana
 5     7 banana
 6     3 banana
 7     8 lime  
 8    10 lime  
 9     5 lime  
  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.