简体   繁体   English

Pivot 到具有指定列数的 data.frame 的字符向量

[英]Pivot a character vector to a data.frame with specified number of columns

I have a vector of data where every 4th row starts a new observation.我有一个数据向量,其中每 4 行开始一个新的观察。 I need to pivot the data so that first four values become the first row, the next four values become the second, and so on.我需要 pivot 数据,以便前四个值成为第一行,接下来的四个值成为第二行,依此类推。

Here is a simplified example...这是一个简化的例子......

Given the following data:给定以下数据:

a <- rep(c("a", "b", "c", "d"), 3)

The desired output is:所需的 output 是:

  A_lab B_lab C_lab D_lab
1     a     b     c     d
2     a     b     c     d
3     a     b     c     d

If you want a matrix, just call:如果你想要一个矩阵,只需调用:

matrix(a, ncol=4, byrow=TRUE)

     [,1] [,2] [,3] [,4]
[1,] "a"  "b"  "c"  "d" 
[2,] "a"  "b"  "c"  "d" 
[3,] "a"  "b"  "c"  "d"

For a data.frame, pipe that result into data.frame:对于 data.frame,pipe 生成 data.frame:

data.frame(matrix(a, ncol=4, byrow=TRUE))

  X1 X2 X3 X4
1  a  b  c  d
2  a  b  c  d
3  a  b  c  d

Here's an option using dplyr and the tidyverse这是使用 dplyr 和 tidyverse 的选项

require(tidyverse)
a <- rep(c("a", "b", "c", "d"), 3)

labs = rep(c("A_lab", "B_lab", "C_lab", "D_lab"), 3)
obs_id <- rep(1:3, each=length(unique(a)))


tibble(vals = a, labs = labs,  obs_id = obs_id) %>%
  pivot_wider(obs_id, values_from = vals, names_from = labs)


# A tibble: 3 x 5
#  obs_id A_lab B_lab C_lab D_lab
#   <int> <chr> <chr> <chr> <chr>
#1      1 a     b     c     d    
#2      2 a     b     c     d    
#3      3 a     b     c     d 
a <- rep(c("a", "b", "c", "d"), 3)

library(tidyverse)
a %>% as.data.frame() %>% setNames('V') %>%
  mutate(dummy = (( row_number() -1) %% 4)+1) %>%
  pivot_wider(names_from = dummy, values_from = V, values_fn = list) %>%
  unnest(everything())
#> # A tibble: 3 x 4
#>   `1`   `2`   `3`   `4`  
#>   <chr> <chr> <chr> <chr>
#> 1 a     b     c     d    
#> 2 a     b     c     d    
#> 3 a     b     c     d

Created on 2021-06-01 by the reprex package (v2.0.0)reprex package (v2.0.0) 于 2021 年 6 月 1 日创建

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

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