通过一定数量的线对DF进行转移

发布于 2025-02-01 02:47:39 字数 586 浏览 3 评论 0原文

假设我有一个看起来像这样的数据框架:

mydf <- data.frame(col0=c("row1","row2","row3"),
                     col1=c(AAA1),
                     col2=c(BBB1),
                     col3=c(CCC1),
                     col4=c(AAA2),
                     col5=c(BBB2),
                     col6=c(CCC2))
mydf
# col0 col1
# row1 AAA1
# row2 BBB1
# row3 CCC1
# row4 AAA2
# row5 BBB2
# row6 CCC2

我希望每3行每3行对其进行转换,这样看起来像这样:

# col0 col1 col2 col3
# row1 AAA1 BBB1 CCC1
# row2 AAA2 BBB2 CCC2

我该怎么做?是否有这种转换的功能?类似pivot_wider o sprin的东西可以设置为重复每条x行?

Suppose I have a data frame that looks like this:

mydf <- data.frame(col0=c("row1","row2","row3"),
                     col1=c(AAA1),
                     col2=c(BBB1),
                     col3=c(CCC1),
                     col4=c(AAA2),
                     col5=c(BBB2),
                     col6=c(CCC2))
mydf
# col0 col1
# row1 AAA1
# row2 BBB1
# row3 CCC1
# row4 AAA2
# row5 BBB2
# row6 CCC2

I'd like it to be transposed every 3 lines, so that it looks like this:

# col0 col1 col2 col3
# row1 AAA1 BBB1 CCC1
# row2 AAA2 BBB2 CCC2

How could I make this? Is there any function that does this kind of transposing? Something like a pivot_wider ou spread that could be set to repeat every X lines?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

被你宠の有点坏 2025-02-08 02:47:39

您需要添加一个枢轴列和一个端ID列,以免崩溃:

df <- data.frame(
    col0 = c("a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3")
)

print(df)

 col0
1   a1
2   b1
3   c1
4   a2
5   b2
6   c2
7   a3
8   b3
9   c3

现在,转换:

df <- df %>% 
    mutate(
        col_pivot = rep(1:3, length.out = nrow(.)),
        end_id = rep(1:(nrow(.)/3), each = 3) # this prevents the dataframe from collapsing to 1 row
        ) %>% 
    pivot_wider(
        names_from = col_pivot,
        names_prefix = "col_",
        values_from = col0
    )

print(df)

# A tibble: 3 × 4
  end_id col_1 col_2 col_3
   <int> <chr> <chr> <chr>
1      1 a1    b1    c1   
2      2 a2    b2    c2   
3      3 a3    b3    c3  

You need to add a pivot column and an end id column so it does not collapse:

df <- data.frame(
    col0 = c("a1", "b1", "c1", "a2", "b2", "c2", "a3", "b3", "c3")
)

print(df)

 col0
1   a1
2   b1
3   c1
4   a2
5   b2
6   c2
7   a3
8   b3
9   c3

Now, the transformation:

df <- df %>% 
    mutate(
        col_pivot = rep(1:3, length.out = nrow(.)),
        end_id = rep(1:(nrow(.)/3), each = 3) # this prevents the dataframe from collapsing to 1 row
        ) %>% 
    pivot_wider(
        names_from = col_pivot,
        names_prefix = "col_",
        values_from = col0
    )

print(df)

# A tibble: 3 × 4
  end_id col_1 col_2 col_3
   <int> <chr> <chr> <chr>
1      1 a1    b1    c1   
2      2 a2    b2    c2   
3      3 a3    b3    c3  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文