2017-10-17 80 views
0

这里是样本数据:如何data.frame拆分等于列

df <- data.frame(t(data.frame(seq(1,10,1)))); rownames(df) <- NULL; 
colnames(df) <- letters[1:ncol(df)] 
df 

我想安排新data.frame,使其始终具有6列,下一行(因为夹板的NcoI后> 6)将包含接下来的6列名称和下一行的值。最后一行if ncol < 6这些值用包含列名的空字符串填充。

在这里期望的输出:

a b c d e f 
1 1 2 3 4 5 6 
2 g h i j 
3 7 8 9 10 

又如:

df <- data.frame(t(data.frame(seq(1,15,1)))); rownames(df) <- NULL; 
colnames(df) <- letters[1:ncol(df)] 
df 

    a b c d e f 
1 1 2 3 4 5 6 
2 g h i j k l 
3 7 8 9 10 11 12 
4 m n o 
5 13 14 15 

编辑:

到可能接近它的方法是:

n <- 6 
ncl <- nrow(df) 

s <- split(df, rep(1:ceiling(ncl/n), each=n, length.out=ncl)) 
s 

s1 <- split(rownames(df), rep(1:ceiling(ncl/n), each=n, length.out=ncl)) 
s1 

结合每秒的s PLIT和s1

s1[c(TRUE,FALSE)] 

回答

1

这里有一个方法,不那么漂亮,但是这是一个丑陋的问题:d

library(tibble) 
library(dplyr) 
df1 <- matrix(c(names(df),rep('',6 - ncol(df)%%6)) %>% unlist, ncol=6,byrow=T) %>% as_tibble %>% rowid_to_column() 
df2 <- matrix(c(df  ,rep('',6 - ncol(df)%%6)) %>% unlist, ncol=6,byrow=T) %>% as_tibble %>% rowid_to_column() 
bind_rows(df1,df2) %>% arrange(rowid) %>% select(-1) %>% setNames(.[1,]) %>% slice(-1) 

# # A tibble: 3 x 6 
#  a  b  c  d  e  f 
# <chr> <chr> <chr> <chr> <chr> <chr> 
# 1  1  2  3  4  5  6 
# 2  g  h  i  j    
# 3  7  8  9 10 
1

对于我的生活,我不能想出一个用例这个...但所提供的例子着想......

seq(1, ncol(df), by = 6) %>% { 
    starts <- . 
    ends <- c(lead(.,1,NULL)-1, ncol(df)) 
    base_df <- df[,starts[[1]]:ends[[1]]] 
    rbind(base_df, rbind.pages(Map(function(s, e){ 
     d <- df[,seq(s, e)] 
     data.frame(rbind(colnames(d), d)) %>% setNames(colnames(base_df)[1:length(.)]) 
    }, s = starts[-1], e = ends[-1])) 
     ) %>% 
     mutate_all(function(x){ 
      ifelse(!is.na(x), x, "") 
     }) 
} 

    a b c d e f 
1 1 2 3 4 5 6 
2 g h i j k l 
3 7 8 9 10 11 12 
4 m n o   
5 13 14 15 

编辑强迫NA为“空字符串”

+0

它适用于该示例,但不适用于实际数据。这个解决方案对于这个任务来说太复杂了(丑陋的黑客攻击),这让我想到如何使它适应需求。你也需要'jsonlite'包来使它工作,并且'rbind.pages'不被弃用,而是使用'rbind_pages'。谢谢。 – Maximilian

+0

这没有给出所需的输出 –

+0

编辑...复制在错误的行。道歉... –