简体   繁体   English

如何在R的一行中将多行转换为多列

[英]How to convert multiple rows into multiple columns in one row in r

I have data in this form 我有这种形式的数据

         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

and I want to convert it into 我想将其转换为

         V1    V2    V3    V4

1        6     1     5

2        1     0     6     385

3        5     4     6      98

4        0     1     2

any suggestions to do it into r 任何建议做到R

Please see the following and let me know if this works for you: 请查看以下内容,让我知道这是否适合您:

# 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

Here is a dplyr/tidyr solution. 这是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)

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

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