2017-08-13 18 views
1

假设我有一个数据帧:向下移动在数据帧列中的R

df<-data.frame(step1=c(1,2,3,4),step2=c(5,6,7,8),step3=c(9,10,11,12),step4=c(13,14,15,16)) 

    step1 step2 step3 step4 
1  1  5  9 13 
2  2  6 10 14 
3  3  7 11 15 
4  4  8 12 16 

什么,我需要做的就是像下面这样:

df2<-data.frame(col1=c(1,2,3,4,5,6,7,8,9,10,11,12),col2=c(5,6,7,8,9,10,11,12,13,14,15,16)) 

    col1 col2 
1  1 5 
2  2 6 
3  3 7 
4  4 8 
5  5 9 
6  6 10 
7  7 11 
8  8 12 
9  9 13 
10 10 14 
11 11 15 
12 12 16 

我怎么能这样做?考虑可以包括更多步骤(例如,20个步骤)。

谢谢!

回答

1

我们可以设计一个函数来实现这个任务。 df_final是最终的输出。请注意,bin是一个参数,用户可以指定一起转换多少个列。

# A function to conduct data transformation 
trans_fun <- function(df, bin = 3){ 
    # Calculate the number of new columns 
    new_ncol <- (ncol(df) - bin) + 1 
    # Create a list to store all data frames 
    df_list <- lapply(1:new_ncol, function(num){ 
    return(df[, num:(num + bin - 1)]) 
    }) 
    # Convert each data frame to a vector 
    dt_list2 <- lapply(df_list, unlist) 
    # Convert dt_list2 to data frame 
    df_final <- as.data.frame(dt_list2) 
    # Set the column and row names of df_final 
    colnames(df_final) <- paste0("col", 1:new_ncol) 
    rownames(df_final) <- 1:nrow(df_final) 
    return(df_final) 
} 

# Apply the trans_fun 
df_final <- trans_fun(df) 

df_final 
    col1 col2 
1  1 5 
2  2 6 
3  3 7 
4  4 8 
5  5 9 
6  6 10 
7  7 11 
8  8 12 
9  9 13 
10 10 14 
11 11 15 
12 12 16 
1

这应该做的工作:

df2 <- data.frame(col1 = 1:(length(df$step1) + length(df$step2))) df2$col1 <- c(df$step1, df$step2, df$step3) df2$col2 <- c(df$step2, df$step3, df$step4)

观光点:

  • 代码的第一行看到最重要的事情,是创造需求一个具有适量行的表格
  • 调用不存在的列将创建一个,名称为
  • R中删除列应该做这样DF2 $山坳< - NULL
+0

纠正。谢谢 – theBotelho

1

下面是使用dplyrreshape2的方法 - 这是假定所有列的长度相同。

library(dplyr) 
library(reshape2) 

从数据帧

df[,1:ncol(df)-1]%>% 
    melt() %>% 
    dplyr::select(col1=value) -> col1 

下降,由数据帧

df %>% 
    dplyr::select(-step1) %>% 
    melt() %>% 
    dplyr::select(col2=value) -> col2 

第一列拖放最后一列合并dataframes

bind_cols(col1, col2) 
1

你不要光看要做:

df2 <- data.frame(col1 = unlist(df[,-nrow(df)]), 
        col2 = unlist(df[,-1])) 
rownames(df2) <- NULL 
df2 
col1 col2 
1  1 5 
2  2 6 
3  3 7 
4  4 8 
5  5 9 
6  6 10 
7  7 11 
8  8 12 
9  9 13 
10 10 14 
11 11 15 
12 12 16