Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (50.2k points)

From the data frame:

              TimeStamp      Fab23.A   start.end

1   2020-03-02 20:44:00     27.54236       start

2   2020-03-02 20:50:00    186.08670         end

3   2020-03-03 18:12:00     37.33132       start

4   2020-03-03 18:16:00    189.78060         end

5   2020-03-04 17:48:00     33.78360       start

6   2020-03-04 17:52:00    190.08100         end

.

.

.

I want to reshape them to the below format based on the last categorical value of the last column:

        start.TimeStamp          end.TimeStamp    start.Fab23.A    start.Fab23.A

1   2020-03-02 20:44:00    2020-03-02 20:50:00         27.54236        186.08670     

2   2020-03-03 18:12:00    2020-03-03 18:16:00         37.33132        189.78060    

3   2020-03-04 17:48:00    2020-03-04 17:52:00         33.78360        190.08100    

.

.

.

1 Answer

0 votes
by (107k points)

You can simply use the following code:

library(dplyr)

df %>%

  group_by(start.end) %>%

  mutate(row = row_number()) %>%

  tidyr::pivot_wider(names_from = start.end, 

                    values_from = c(TimeStamp, Fab23.A)) %>%

  select(-row)

# A tibble: 3 x 4

#  TimeStamp_start    TimeStamp_end      Fab23.A_start Fab23.A_end

#  <chr>              <chr>                      <dbl>       <dbl>

#1 2020-03-0220:44:00 2020-03-0220:50:00          27.5        186.

#2 2020-03-0318:12:00 2020-03-0318:16:00          37.3        190.

#3 2020-03-0417:48:00 2020-03-0417:52:00          33.8        190.

Here the data is:

df <- structure(list(TimeStamp = c("2020-03-0220:44:00", "2020-03-0220:50:00", 

"2020-03-0318:12:00", "2020-03-0318:16:00", "2020-03-0417:48:00", 

"2020-03-0417:52:00"), Fab23.A = c(27.54236, 186.0867, 37.33132, 

189.7806, 33.7836, 190.081), start.end = c("start", "end", "start", 

"end", "start", "end")), class = "data.frame", row.names = c(NA, -6L))

If you are interested in R certification then do refer to the R programming certification

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...