[英]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.