首页 > 解决方案 > R中的索引列问题

问题描述

我正在尝试读取一个 csv 文件,它在执行 read.csv 时看起来像这样

df = read.csv("df.csv", header = FALSE, sep = ",", skipNul = TRUE)

  V1   V2   V3   V4
1 my 
2 Col1 Col2 Col3 Col4
3 1    2    3    a  
4 1    5    2    a
5 1    5    3    a

我必须设置 header = FALSE 否则文件不会被读取,因为第一行有那个奇怪的“我的”字符串。

我想将列索引设置为 Col1、Col2、Col3、Col4。我试过这个但它不起作用:

df <- df[-1,] #use negative indexing to remove first row

colnames[df] <- df[1,] #change colnames index

Output:

      Col1 Col2 Col3 Col4 
    2 Col1 Col2 Col3 Col4
    3 1    2    3    a  
    4 1    5    2    a
    5 1    5    3    a

我该如何解决这个问题以实现我想要的?

标签: rcsv

解决方案


正如@Ronak Shah 指出的那样,skip = 1 有效并解决了问题


推荐阅读