1

CSV ファイルからデータ フレームにデータを読み込もうとしています。データには、要因として持ちたくない名前が含まれています。stringAsFactors=FALSE要因として持ちたい他の列があるため、引数を使用できません。

目的の動作を実現するにはどうすればよいですか?

注:データには何千もの列があります...1つの列のデータ型のみを変更する必要があります..残りのデフォルトで割り当てられた型はすべて問題ありません

4

3 に答える 3

5

colClasses引数を使用して、各列のタイプを指定します。例えば:

x <- read.csv("myfile.csv", colClasses=c("numeric","factor","character"))
于 2013-01-25T14:59:58.647 に答える
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).

次のようなものです:

types = c("numeric", "character", "factor")
read.table("file.txt", colClasses = types)

トリックを行う必要があります。

個人的には、列を文字列または要素として読み取り、必要な列を変更します。

于 2013-01-25T15:00:07.670 に答える
1

前の回答のドキュメントに記載されているように、データを読み込む前に列の名前がわかっている場合は、名前付き文字ベクトルを使用してその列のみを指定できます。

types <- c(b="character") #Set the column named "b" to character
df <- read.table(header=TRUE,sep=",",colClasses=types,text="
a,b,c,d,e
1,asdf,morning,4,greeting
5,fiewhn,evening,12,greeting
9,ddddd,afternoon,292,farewell
33,eianzpod,evening,1111,farewell
191,dnmxzcv,afternoon,394,greeting
")
sapply(df,class)
#          a           b           c           d           e 
#  "integer" "character"    "factor"   "integer"    "factor" 

ヘッダーがない場合は、位置で行うこともできます。

types <- c(V2="character") #Set the second column to character
df <- read.table(header=FALSE,sep=",",colClasses=types,text="
1,asdf,morning,4,greeting
5,fiewhn,evening,12,greeting
9,ddddd,afternoon,292,farewell
33,eianzpod,evening,1111,farewell
191,dnmxzcv,afternoon,394,greeting
")
sapply(df,class)
#       V1          V2          V3          V4          V5 
#"integer" "character"    "factor"   "integer"    "factor" 

最後に、位置がわかっているがヘッダーがある場合は、適切な長さのベクトルを作成できます。の場合colClassesNAはデフォルトを意味します。

types <- rep.int(NA_character_,5) #make this length the number of columns
types[2] <- "character" #force the second column as character
df <- read.table(header=TRUE,sep=",",colClasses=types,text="
a,b,c,d,e
1,asdf,morning,4,greeting
5,fiewhn,evening,12,greeting
9,ddddd,afternoon,292,farewell
33,eianzpod,evening,1111,farewell
191,dnmxzcv,afternoon,394,greeting
")
sapply(df,class)
#       V1          V2          V3          V4          V5 
#"integer" "character"    "factor"   "integer"    "factor" 
于 2013-01-25T15:45:41.903 に答える