使第一行成为r中数据帧的标题

时间:2015-06-19 08:03:48

标签: r header

我在这里问过这个问题:Create header of a dataframe from the first row in the data frame

在这里:assign headers based on existing row in dataframe in R

并且提供的解决方案对我不起作用。

当我转置我的数据帧(p1)时,DF.transpose(p1t)的标题是新的和令人讨厌的东西。而p1t的第一行是我想用作标题的,我试过了:

    colnames(p1t) = p1t[1, ] 

并且它不起作用!

这是原始df的显示方式:

    File Fp1.PD_ShortSOA_FAM Fp1.PD_LongSOA_FAM Fp1.PD_ShortSOA_SEMplus_REAL Fp1.PD_ShortSOA_SEMplus_FICT
    sub0001            0,446222          2,524,804            0,272959                    1,281,349
    sub0002           1,032,688          2,671,048           1,033,278                    1,217,817

以下是转置的出现方式:

    row.names                            V1         V2
    File                            sub0001    sub0002
    Fp1.PD_ShortSOA_FAM            0,446222  1,032,688
    Fp1.PD_LongSOA_FAM            2,524,804  2,671,048
    Fp1.PD_ShortSOA_SEMplus_REAL   0,272959  1,033,278
    Fp1.PD_ShortSOA_SEMplus_FICT  1,281,349  1,217,817
    Fp1.PD_ShortSOA_SEMminus_REAL  0,142739  1,405,100
    Fp1.PD_ShortSOA_SEMminus_FICT 1,515,577 -1,990,458

如何制作"文件"," sub0001"," sub0002"等...作为标题?

谢谢!

2 个答案:

答案 0 :(得分:2)

适合我(带一点小窍门)。

x <- read.table(text = "File Fp1.PD_ShortSOA_FAM Fp1.PD_LongSOA_FAM Fp1.PD_ShortSOA_SEMplus_REAL Fp1.PD_ShortSOA_SEMplus_FICT
    sub0001            0,446222          2,524,804            0,272959                    1,281,349
    sub0002           1,032,688          2,671,048           1,033,278                    1,217,817",
                header = TRUE)

x <- t(x)
colnames(x) <- x[1, ]
x <- x[-1, ]
x

                             sub0001     sub0002    
Fp1.PD_ShortSOA_FAM          "0,446222"  "1,032,688"
Fp1.PD_LongSOA_FAM           "2,524,804" "2,671,048"
Fp1.PD_ShortSOA_SEMplus_REAL "0,272959"  "1,033,278"
Fp1.PD_ShortSOA_SEMplus_FICT "1,281,349" "1,217,817"

答案 1 :(得分:1)

我们可以利用transpose中的data.table

library(janitor)
data.table::transpose(x, keep.names = 'File') %>%
           row_to_names(1)
#                          File   sub0001   sub0002
#2          Fp1.PD_ShortSOA_FAM  0,446222 1,032,688
#3           Fp1.PD_LongSOA_FAM 2,524,804 2,671,048
#4 Fp1.PD_ShortSOA_SEMplus_REAL  0,272959 1,033,278
#5 Fp1.PD_ShortSOA_SEMplus_FICT 1,281,349 1,217,817

数据

x <- structure(list(File = structure(1:2, .Label = c("sub0001", "sub0002"
), class = "factor"), Fp1.PD_ShortSOA_FAM = structure(1:2, .Label = c("0,446222", 
"1,032,688"), class = "factor"), Fp1.PD_LongSOA_FAM = structure(1:2, .Label = c("2,524,804", 
"2,671,048"), class = "factor"), Fp1.PD_ShortSOA_SEMplus_REAL = structure(1:2, .Label = c("0,272959", 
"1,033,278"), class = "factor"), Fp1.PD_ShortSOA_SEMplus_FICT = structure(2:1, .Label = c("1,217,817", 
"1,281,349"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))