簡體   English   中英

數據框從數字變為字符

[英]Data frame changes from numeric to character

我打開csv文件,並控制每個數據的類:

mydataP<-read.csv("Energy_protein2.csv", stringsAsFactors=F) 

apply(mydataP, 2, function(i) class(i))
#[1] "numeric" 

我添加一列並檢查數據的類:

mydataP[ ,"ID"] <-rep(c("KOH1", "KOH2", "KOH3", "KON1", "KON2", "KON3", "WTH1", "WTH2", "WTH3","WTN1", "WTN2", "WTN3"), each=2)

apply(mydataP, 2, function(i) class(i))

在這里它變成一個“字符”

as.numeric(as.factor(mydataP))
#Error in sort.list(y) : 'x' must be atomic for 'sort.list'
#Have you called 'sort' on a list?

as.numeric(as.character(mydataP))

我得到117 NA的向量

我不知道現在該怎么辦,一旦我觸摸到框架變成了性格,有人可以幫我嗎? 謝謝

這是因為apply轉換您的data.frame到matrix和那些只能有一個班在其中。

嘗試以下方法:

sapply(mydataP, class)

這就是您通常應避免在data.frame上使用apply的原因。

幫助文件( ?apply )中記錄了此行為:

如果X不是數組,而是具有非null暗值的類的對象(例如數據幀),則如果X是二維的(例如,數據),則嘗試通過as.matrix將其強制到數組。框架)或通過as.array。


這是內置虹膜數據集的可重現示例:

> apply(iris, 2, function(i) class(i))
#Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
# "character"  "character"  "character"  "character"  "character" 

> sapply(iris, class)
#Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#   "numeric"    "numeric"    "numeric"    "numeric"     "factor" 

> str(iris)
#'data.frame':  150 obs. of  5 variables:
# $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

如您所見, apply將所有列轉換為同一類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM