在創建內容包含重複值的列時,我注意到以下因素。一列如何被確定爲數據框中的類因子?
1.如果在數據框創建時將具有重複字符值的列作爲數據框的一部分,則它屬於類因子,但如果稍後添加相同的列,則它是類別字符,兩種情況下的值都是相同的。爲什麼是這樣?
#creating a data frame
name = c('waugh','waugh','smith')
age = c(21,21,27)
df = data.frame(name,age)
#adding a new column which has the same values as the 'name' column above, to the data frame
df$newcol = c('waugh','waugh','smith')
#you can see that the class'es of the two are different though the values are same
class(df$name)
## [1] "factor"
class(df$newcol)
## [1] "character"
只有其具有重複字母內容的列成爲一個因素;如果某列包含重複的數值,則不會將其視爲一個因子。這是爲什麼?我很可能意味着1-Male,0-Female,在這種情況下,它應該是一個因素?
注意,這兩列包含重複值
class(df$name) ## [1] "factor" class(df$age) ## [1] "numeric"
請參閱'?data.frame'和'stringsAsFactors'參數。 '$ < - 。data.frame'不會調用'data.frame'構造函數,所以不會發生任何轉換。 –
對Joshua的評論添加的唯一一件事情是,它不是重複的值,這會導致創建因子列,而是data.frame處理_any_字符向量。 (沒有做出「決定」。) –
@JoshuaUlrich謝謝,我在df創建時嘗試過stringsAsFactors = FALSE。我有一個問題,當我添加一個新列像df $ newcol = c('waugh','waugh','smith')時,我該如何將它設置爲TRUE – IAMTubby