将每N行转置为新列

3

我有一个包含数百行的数据框,其中单个列遵循以下模式:

   col1
1.12/17/18
2.10/10
3.Best Movie
4.This is the best movie ever...
5.
6.
7.1/1/2019
8.02/10
9.Worst Movie
10.This movie was awful...

我想知道是否有一种方法可以将范围内的每一行转置为它们自己的列,然后依次堆叠下一个范围的4个列在新列下面?
因此,最终输出如下:
Date         Rating     Title       Review
12/17/18      10/10     Best Movie  This is the best movie ever...
1/1/2019      02/10     Worst Movie This movie was awful...

你有什么建议,可以让我如何修改数据框以实现这一目标?


我想补充一下@alistaire的解决方案,你可能需要先过滤掉空行(例如你示例中的第5-6行)。 - iod
非常类似于这个旧问题 - https://dev59.com/H23Xa4cB1Zd3GeqPis38 - thelatemail
2个回答

4

如果每个记录的列数相同,我会先将其包装到一个矩阵中。使用 @alistaire 的数据:

out <- as.data.frame(matrix(df$col1[df$col1!=""], ncol=4, byrow=TRUE))
names(out) <- c('Date', 'Rating', 'Title', 'Review')
out
#      Date Rating       Title                         Review
#1 12/17/18  10/10  Best Movie This is the best movie ever...
#2 1/1/2019  02/10 Worst Movie        This movie was awful...

你甚至可以使用scanmulti.line=TRUE参数一次性将其整合在一起:

out <- data.frame(scan(text=df$col1[df$col1 != ""], multi.line=TRUE, what=rep(list(""), 4), sep="\n"))
names(out) <- c('Date', 'Rating', 'Title', 'Review')
out
#      Date Rating       Title                         Review
#1 12/17/18  10/10  Best Movie This is the best movie ever...
#2 1/1/2019  02/10 Worst Movie        This movie was awful...
< p > scan 的好处是您还可以在 what= 参数中指定输出格式。因此,如果第2列是整数,您可以执行以下操作:

scan(file, multi.line=TRUE, what=list("",1L,"",""), sep="\n")

3

这基本上是一种长宽变换,但需要创建一个键列(即将成为列名)和一个ID列以清楚地确定哪些值进入哪些行。在整洁语法中,

library(tidyverse)

df <- data.frame(
    col1 = c("12/17/18", "10/10", "Best Movie", "This is the best movie ever...", "", "", "1/1/2019", "02/10", "Worst Movie", "This movie was awful..."), 
    stringsAsFactors = FALSE
)

df %>% 
    filter(col1 != '') %>%    # drop empty rows
    mutate(key = rep(c('Date', 'Rating', 'Title', 'Review'), n() / 4), 
           id = cumsum(key == 'Date')) %>% 
    spread(key, col1)
#>   id     Date Rating                         Review       Title
#> 1  1 12/17/18  10/10 This is the best movie ever...  Best Movie
#> 2  2 1/1/2019  02/10        This movie was awful... Worst Movie

这种数据结构非常脆弱,一点偏差就能导致出现全错乱的情况。更好的解决方案是在数据进入混乱之前,在上游维护好数据结构。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接