将数据读入数据框

Aad*_*mia 1 types r dataframe

我正在尝试将CS​​V文件中的数据读入数据框.数据包含我不想要的名称作为因素.我不能使用这个stringAsFactors=FALSE参数,因为我想要其他列作为因素.

我如何实现理想的行为?

注意:数据有数千列...我只需要为一列修改数据类型.默认情况下为其余列分配的类型都很好

Jos*_*ich 5

使用colClasses参数指定每列的类型.例如:

x <- read.csv("myfile.csv", colClasses=c("numeric","factor","character"))
Run Code Online (Sandbox Code Playgroud)


csg*_*pie 5

您可以指定列类.从 ?read.table

colClasses: character.  A vector of classes to be assumed for the
      columns.  Recycled as necessary, or if the character vector
      is named, unspecified values are taken to be 'NA'.

      Possible values are 'NA' (the default, when 'type.convert' is
      used), '"NULL"' (when the column is skipped), one of the
      atomic vector classes (logical, integer, numeric, complex,
      character, raw), or '"factor"', '"Date"' or '"POSIXct"'.
      Otherwise there needs to be an 'as' method (from package
      'methods') for conversion from '"character"' to the specified
      formal class.

      Note that 'colClasses' is specified per column (not per
      variable) and so includes the column of row names (if any).
Run Code Online (Sandbox Code Playgroud)

所以类似于:

types = c("numeric", "character", "factor")
read.table("file.txt", colClasses = types)
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.

就个人而言,我只是以字符串因子的形式读取列,然后更改所需的列.

  • +1为两步法.这是我大部分时间都在使用的. (3认同)