如何防止将数据框列分类为字符而不是数字 [英] how to prevent dataframe columns being classed as character instead of numeric
问题描述
早上好。
我正骑自行车穿过一些数据,在我走的时候建立一个数据框。每次添加或替换数据帧中的一行时,数值将被归类为字符,我必须重新分类。我假设在将数据添加到数据框中时,我做错了什么?
I am cycling through some data, building a dataframe as I go. Every time I add or replace a row in the dataframe, numeric values get classed as character, and I have to re-class them. I assume I am doing something wrong when adding the data to the dataframe ?
test.df<-data.frame(SIDE=rep("",5),n=rep(NA, 5),c1=rep(NA,5),stringsAsFactors=FALSE)
test.df[1,]<-cbind("A",1,256)
test.df[2,]<-cbind("A",2,258)
test.df[3,]<-cbind("A",3,350)
test.df[4,]<-cbind("A",4,400)
test.df[5,]<-cbind("A",5,360)
summary(test.df)
SIDE n c1
Length:5 Length:5 Length:5
Class :character Class :character Class :character
Mode :character Mode :character Mode :character
将数字列转换为数字:
test.df[, c(2:3)] <- sapply(test.df[, c(2:3)], as.numeric)
summary(test.df)
SIDE n c1
Length:5 Min. :1 Min. :256.0
Class :character 1st Qu.:2 1st Qu.:258.0
Mode :character Median :3 Median :350.0
Mean :3 Mean :324.8
3rd Qu.:4 3rd Qu.:360.0
Max. :5 Max. :400.0
所以数据框现在是我预期的 - 1列字符数据和2个数字。但是,如果我再次更改一个行:
So the dataframe is now as I expect it - 1 column of character data and 2 of numeric. However if I change one of the rows again:
test.df[5,]<-cbind("A",5,360)
summary(test.df)
SIDE n c1
Length:5 Length:5 Length:5
Class :character Class :character Class :character
Mode :character Mode :character Mode :character
它已经回到所有角色!
有没有办法确保在数据框中附加/更改数据时保留适当的类?
Is there any way to ensure that when I append/change data in the dataframe that it keeps the appropriate classes ?
谢谢, Pete
推荐答案
cbind(A,5,360)
,它只能保存一种类型,即您的案例中的字符。
cbind("A",5,360)
is a matrix, which can hold only one type, i.e. character in your case.
使用data.frame方法:
Use the data.frame method:
cbind.data.frame("A",5,360)
然而,骑自行车通过一些数据可能是在R中执行此操作的最不有效的方法。
However, "cycling through some data" is probably the least efficient way to do this in R.
这篇关于如何防止将数据框列分类为字符而不是数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!