1

The dataset is as follows:

enter image description here

The output should be as follows

enter image description here

I have tried the following things

  1. sum <- gather(Learning_platform, A,B) I used the gather function from tidyr, but it did not give me the desired result. It just gathered the data and separated it by underscores.

2.df %>% group_by(A) %>% summarise(B = sum(B)) This also did not work as the sum of factors could not be processed by R.

  1. I also used the following example from the tidyr package to no avail:

df %>% group_by(A,B) %>% summarise(A,B)) %>% spread(ID, A,B,C,D) %>% ungroup() %>%

Kindly suggest a solution or learning material for the above example.

marine8115
  • 588
  • 3
  • 22

2 Answers2

3

We can use gather

library(tidyverse)
gather(df1, key, val, - ID) %>%
    filter(val != "") %>%
    select(-key) %>%
    arrange(ID)

If the blank is NA, then we can remove those elements within the gather itself

gather(df1, key, val, -ID, na.rm = TRUE) %>%
    select(-key) %>%
    arrange(ID)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

We can also use reshape2.

reshape(df, idvar = "ID", varying = list(2:5), direction = "long") %>%
  arrange(ID) %>% select(-time)
hpesoj626
  • 3,529
  • 1
  • 17
  • 25