如何防止数据框列被归类为字符而不是数字

时间:2013-08-05 06:55:22

标签: r 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列数字。但是,如果我再次更改其中一行:

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  

它又回到了所有角色!

有什么方法可以确保当我在数据框中追加/更改数据时它保留了相应的类?

谢谢,皮特

3 个答案:

答案 0 :(得分:6)

cbind("A",5,360)是一个矩阵,它只能包含一种类型,即你的情况下的字符。

使用data.frame方法:

cbind.data.frame("A",5,360)

然而,“在某些数据中循环”可能是在R中执行此操作的效率最低的方法。

答案 1 :(得分:4)

当你形成矩阵时,它都是相同的模式,所以这个cbind("A",1,256)都是字符模式。 (有一个cbind.data.frame函数,但cbind的参数都不是data.frames,所以它没有被调用。你可以这样做:

test.df<-data.frame(SIDE="A",n=1,c1=256,stringsAsFactors=FALSE)
test.df<- rbind( test.df,
                  list("A",2,258),
                  list("A",3,350),
                  list("A",4,400),
                  list("A",5,360) )
 test.df
#---------------    
  SIDE n  c1
1    A 1 256
2    A 2 258
3    A 3 350
4    A 4 400
5    A 5 360

答案 2 :(得分:1)

刚遇到类似的问题,最快的方式(我认为)是设置options(stringsAsFactors=FALSE)