首页 > 解决方案 > 将每 5 个观察值发送到 r 中的下一行

问题描述

我是 R 新手,我的数据集有问题。我创建了一个数据框,我的所有数据都在 1 行中,我需要将每 5 个观察值发送到下一行:

My current dataset called ndf: 

  Col_1  Col_2  Col_3  Col_4 ... Col_4005 
1 text1  text2  text3  text4     text4005 

What I need: 

    Col_1     Col_2     Col_3     Col_4     Col_5 
1   text1     text2     text3     text4     text5 
2   text6     text7     text8     text9     text10 
...
801 text4001  text4002  text4003  text4004  text4005

我怎样才能做到这一点?

我尝试使用循环,但它不起作用。我还使用了这个不起作用的功能:

ndf<-ndf[rep(seq_len(ncol(ndf)), each = 5), ]

标签: rtext-mining

解决方案


您可以使用matrix

matrix(ndf, ncol=5, byrow=TRUE)
#     [,1]     [,2]     [,3]     [,4]     [,5]    
#[1,] "text1"  "text2"  "text3"  "text4"  "text5" 
#[2,] "text6"  "text7"  "text8"  "text9"  "text10"
#[3,] "text11" "text12" "text13" "text14" "text15"
#[4,] "text16" "text17" "text18" "text19" "text20"

数据:

ndf <- data.frame(t(paste0("text", 1:20)))

推荐阅读