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

标签 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  

它已经回到了所有的角色!

有什么方法可以确保当我在数据框中附加/更改数据时,它会保留适当的类?

谢谢,皮特

最佳答案

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

使用 data.frame 方法:

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

然而,在 R 中,“循环访问一些数据”可能是效率最低的方法。

关于r - 如何防止数据框列被归类为字符而不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18052167/

相关文章:

python - Pandas 选择具有特定列中前 2 个值之一的所有行

python - Pyspark 数据帧 : Transforming unique elements in rows to columns

python - pandas groupby 在数据帧上并分配回原始 df 因转换失败

python - 在 R 或 Python 中迭代数据集并定位行索引

c++ - Rcpp,使用long long vector 创建数据框

r - 用 3 个点定义 S4 方法

pandas - 根据同一数据框中的其他行从数据框中删除行

python : group by columns with columns values that are grouped by occurs only once and retain all other columns

python - 使用 R 或 Python 将数据框列中的字符串与另一个数据框列中的字符串匹配

r - 如何更改集群中每个组的树状图颜色