2017-06-20 95 views
0

我有數據以這種形式如何多行轉換成多列在一排中的R

  V1 V2 

1  6  1 

2  6  5 

3  1  0 

4  1  6 

5  1 385 

6  5  4 

7  5  6 

8  5 98 

9  0  1 

10  0  2 

,我想將其轉換成

  V1 V2 V3 V4 

1  6  1  5 

2  1  0  6  385 

3  5  4  6  98 

4  0  1  2 

任何建議做成R

+0

如果你只對V1矢量的值感興趣,也許'split'對你有用。否則,搜索「在R中重新整形」。 – lmo

+1

You van使用'tidyr :: nest(df,V2)'創建列表列 – HubertL

+0

新格式的邏輯是什麼? – CPak

回答

0

請看下面,讓我知道,如果這對你的作品:

# Data 
df <- data.frame(V1 = c(6,6,1,1,1,5,5,5,0,0), V2 = c(1,5,0,6,385,4,6,98,1,2)) 

# Splitting 
df.split <- split(df$V2, df$V1) 

# Combining 
maxLength <- max(rapply(df.split, length)) 
# initialize 
new <- list() 
z <- NULL # hold the object for length editing to include NAs 
for(i in 1:length(df.split)){ 
    z <- df.split[[i]] 
    length(z) <- maxLength 
    new[[i]] <- c(as.numeric(names(df.split))[i], z) 
} 
final <- as.data.frame(do.call(rbind,new)) 
[,1] [,2] [,3] [,4] 
[1,] 0 1 2 NA 
[2,] 1 0 6 385 
[3,] 5 4 6 98 
[4,] 6 1 5 NA 
0

這是一個dplyr/tidyr解決方案。

library(stringr) 
library(dplyr) 
library(tidyr) 

# Create test dataframe 
df <- data.frame(V1 = c(6,6,1,1,1,5,5,5,0,0), 
       V2 = c(1,5,0,6,385,4,6,98,1,2)) 

# Group data by V1 column, pasting all V2 values into one row 
df <- df %>% 
     group_by(V1) %>% 
     summarise(V2 = paste(V2, collapse = ",")) 

# Get the number of columns to separate data into 
cols <- max(str_count(df$V2, ",")) + 1 

# Set temporary column names 
cols <- paste0("col", c(1:cols)) 

# Split V2 column into multiple columns 
df <- df %>% 
     separate(V2, into = cols, sep = ",", fill = "right") 

# Rename columns 
colnames(df) <- paste0("V", c(1:ncol(df))) 

# Convert to integer 
df[] <- lapply(df, as.integer) 
+0

感謝馬特它工作:) –

+0

感謝馬特的幫助。我有另一個問題所有其他列是字符格式有沒有什麼辦法讓他們在整數格式 –

+0

'df [] < - lapply(DF,as.integer)' –