繁体   English   中英

R按行中的名称替换标题

[英]R Replace header by names in row

我想用第一行中的标题替换data.frame的标头。 数据已使用read.xls()导入。 遗憾的是,再次阅读原始文件是没有选择的。

     bad header    here
1    new    header2   here
2    58 3.222     50
3    25 10.000    40
4    5  0.847     152.5
5   15  1.633     98

结果应如下所示:

    new header2   here
1   58  3.222     50
2   25  10.000    40
3   5   0.847     152.5
4   15  1.633     98

谢谢,

马特

假设您的data.frame被称为“mydf”,您可以尝试这样的事情:

df2 <- setNames(mydf[-1, ], mydf[1, ])

但是,您的数据将全部是字符或因素,具体取决于它们最初的读取方式。

str(df2)
# 'data.frame': 4 obs. of  3 variables:
#  $ new    : chr  "58" "25" "5" "15"
#  $ header2: chr  "3.222" "10.000" "0.847" "1.633"
#  $ here   : chr  "50" "40" "152.5" "98"

您可以将其转换如下:

df2[] <- lapply(df2, function(x) type.convert(as.character(x)))
str(df2)
# 'data.frame': 4 obs. of  3 variables:
#  $ new    : int  58 25 5 15
#  $ header2: num  3.222 10 0.847 1.633
#  $ here   : num  50 40 152 98
df2
#   new header2  here
# 2  58   3.222  50.0
# 3  25  10.000  40.0
# 4   5   0.847 152.5
# 5  15   1.633  98.0

假设您的数据名为my.data.frame,只需将第1行分配给标题,然后删除第1行

    #assign row 1 names to the header          
    names(my.data.frame) <- as.character(my.data.frame[1,])

    #delete the first row
    my.data.frame <- my.data.frame[2:nrow(my.data.frame),]

暂无
暂无

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

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