变换数据帧中的命名向量

  • 本文关键字:向量 数据帧 变换 r
  • 更新时间 :
  • 英文 :


我有以下向量:

dput(z1)
c(Measure = "Height", IFS = "12,636.00", IFS = "15,401.00", 
IFS = "15,371.00", IFS = "16,218.00", IFS = "20,975.00", Measure = "Height", 
IFS = "12,258.00", IFS = "12,542.00", IFS = "13,014.00", IFS = "13,508.00", 
IFS = "11,934.00", Measure = "Height", IFS = "5,854.46", IFS = "6,500.39", 
IFS = "5,208.78", IFS = "4,221.37", NA, Measure = "Height", 
IFS = "845.70", IFS = "1,161.30", IFS = "1,217.80", IFS = "875.90", 
IFS = "401.90", Measure = "Height", IFS = "34,416.00", IFS = "33,249.00", 
IFS = "32,942.00", IFS = "33,174.00", IFS = "33,267.00", Measure = "Height", 
IFS = "2,390.00", IFS = "2,269.00", IFS = "1,902.00", IFS = "1,710.20", 
IFS = "1,734.60")

我想把它转换成一个数据帧,看起来像这样:

Measure    IFS          IFS       IFS           IFS          IFS     
Height    12,636.00  15,401.00  15,371.00   16,218.00     20,975.00
Height    12,258.00  12,542.00  13,014.00   13,508.00     11,934.00
Height    5,854.46   6,500.39   5,208.78    4,221.37       NA 

再加上另外三行。即前6个值是一行,依此类推

我试过

z1<-stack(z1) then
z1<-t(z1)
z1<-as.data.frame(z1)
z1<-matrix( z1, ncol=6)

但是数据没有按我需要的方式排列。谢谢

我们可以根据"Height"的存在将split转换为list,并通过rbindmap_dfr进行折叠

library(purrr)
library(dplyr)
z2 <- z1[complete.cases(z1)]
map_dfr(split(z2, cumsum(z2 %in% 'Height')), as.data.frame.list)

-输出

Measure       IFS     IFS.1     IFS.2     IFS.3     IFS.4
1  Height 12,636.00 15,401.00 15,371.00 16,218.00 20,975.00
2  Height 12,258.00 12,542.00 13,014.00 13,508.00 11,934.00
3  Height  5,854.46  6,500.39  5,208.78  4,221.37      <NA>
4  Height    845.70  1,161.30  1,217.80    875.90    401.90
5  Height 34,416.00 33,249.00 32,942.00 33,174.00 33,267.00
6  Height  2,390.00  2,269.00  1,902.00  1,710.20  1,734.60

最新更新