2017-08-13 20 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