简体   繁体   English

在 R 中列出每 n 个具有序列的列

[英]Unlisting every n number of columns with a sequence in R

Sorry for my probably easy to solve question.对不起,我可能很容易解决问题。 I have a dataframe of 400 columns and 17532 rows and I want to unlist this to create another dataframe of 8 columns and 876600 rows.我有一个 400 列和 17532 行的 dataframe,我想取消列出它以创建另一个 8 列和 876600 行的 dataframe。 Basically unlist from 1 to 50, 51 to 100, 101 to 150 etc... However I'm running into some problems:基本上不列出从 1 到 50、51 到 100、101 到 150 等...但是我遇到了一些问题:

flw<-data.frame(matrix(NA, ncol=8, nrow=876600)) ## create an empty dataframe

seq(1,length(fl),by=50) ## sequence of columns which effectively is  '1  51 101 151 201 251 301 351' with length(fl)=400

for (i in seq(1,length(fl),by=50) ){
  flw[i] <- as.data.frame(unlist(fl[i:(i+49)]))
}

I get the error:我得到错误:

Error in `[<-.data.frame`(`*tmp*`, i, value = list(`unlist(fl[(i):(i + 49)])` = c(13.24512,  : 
  new columns would leave holes after existing columns

I don't understand why as it shouldn't leave any holes.我不明白为什么,因为它不应该留下任何漏洞。 It should unlist from 1 to 50, and then 51 to 100 etc and this will be 8 columns x 876600. What am I missing?它应该从 1 到 50,然后从 51 到 100 等不列出,这将是 8 列 x 876600。我错过了什么?

Your problem is the indexing into the flw .您的问题是对flw的索引。 You are using the same index that you are using for fl .您使用的索引与用于fl的索引相同。 You end up trying to assigning to row 1, then row 51. Your holes are rows 2:49.你最终试图分配到第 1 行,然后是第 51 行。你的洞是 2:49 行。

If you're not tidyverse adverse this can be done without the loop using the purrr and dplyr如果你不是 tidyverse 不利的,这可以在没有使用purrrdplyr的循环的情况下完成

purrr::map_dfc(
  seq(1,length(fl),by=50),
  ~dplyr::select(fl, .x:(.x+49)) %>% unlist(),
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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