简体   繁体   中英

ungrouping dataframe in r which is grouped by rows

I have this dataframe

Source: local data frame [159 x 2]
Groups: <by row>

# A tibble: 159 × 2
   session_id requestId
*       <int>    <list>
1        1105 <int [3]>
2        1107 <int [2]>
3        1108 <int [6]>
4        1109 <int [1]>
5        1110 <int [6]>
6        1111 <int [8]>
7        1112 <int [4]>
8        1114 <int [8]>
9        1117 <int [7]>
10       1118 <int [4]>
# ... with 149 more rows

I dont know how to ungroup it or its not working as it is grouped by rows not by some variable ..

I want my output look like something in given pattern/format

 # A tibble: 342 × 2
   session_id requestId
        <int>     <dbl>
1        1105        10
2        1105         3
3        1107        13
4        1107        13
5        1108         4
6        1108         6
7        1109        12
8        1109         5
9        1110         6
10       1110        10

I dont know how to do it ,must be simple if known..Thanks for helping

Edit :-

structure(list(session_id = c(1105L, 1107L, 1108L, 1109L, 1110L, 
1111L, 1112L, 1114L, 1117L, 1118L), requestId = list(c(8L, 14L, 
20L), c(7L, 14L), c(1L, 7L, 8L, 20L, 16L, 17L), 8L, c(1L, 16L, 
17L, 8L, 14L, 20L), c(1L, 7L, 8L, 20L, 4L, 11L, 13L, 14L), c(4L, 
11L, 13L, 14L), c(6L, 8L, 14L, 2L, 4L, 10L, 15L, 18L), c(4L, 
5L, 10L, 16L, 2L, 15L, 18L), c(20L, 1L, 7L, 8L))), .Names = c("session_id", 
"requestId"), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
"data.frame"))

Here's a possible starting point, although it's still missing a reproducible example. Can be edited when we get one:

 tlengths <- sapply( tbl$requestId, length)
#Error in lapply(X = X, FUN = FUN, ...) : object 'tbl' not found
 sessions <- mapply(rep, sessionId, tlengths)
#Error in mapply(rep, sessionId, tlengths) : object 'sessionId' not found
 newtbl <- tibble(session_id=sessions, requestId=unlist(tbl$requestId))
#Error in tibble(session_id = sessions, requestId = unlist(tbl$requestId)) : 
 # could not find function "tibble"
 library(tidyverse)

As -pkumar suggested in comment , I did this using tidyverse's unnest

df = structure(list(session_id = c(1105L, 1107L, 1108L, 1109L, 1110L, 
1111L, 1112L, 1114L, 1117L, 1118L), requestId = list(c(8L, 14L, 
20L), c(7L, 14L), c(1L, 7L, 8L, 20L, 16L, 17L), 8L, c(1L, 16L, 
17L, 8L, 14L, 20L), c(1L, 7L, 8L, 20L, 4L, 11L, 13L, 14L), c(4L, 
11L, 13L, 14L), c(6L, 8L, 14L, 2L, 4L, 10L, 15L, 18L), c(4L, 
5L, 10L, 16L, 2L, 15L, 18L), c(20L, 1L, 7L, 8L))), .Names = c("session_id", 
"requestId"), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
"data.frame"))

library('tidyverse')
unnest(df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM