How to convert a data frame column to numeric type

2019-01-01 06:28发布

How do you convert a data frame column to a numeric type?

16条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 06:58

I would have added a comment (cant low rating)

Just to add on user276042 and pangratz

dat$x = as.numeric(as.character(dat$x))

This will override the values of existing column x

查看更多
明月照影归
3楼-- · 2019-01-01 06:58

Considering there might exist char columns, this is based on @Abdou in Get column types of excel sheet automatically answer:

makenumcols<-function(df){
df<-as.data.frame(df)
cond <- apply(df, 2, function(x) {
  x <- x[!is.na(x)]
  all(suppressWarnings(!is.na(as.numeric(x))))
})
numeric_cols <- names(df)[cond]
df[,numeric_cols] <- apply(df[,numeric_cols],2, as.character) # deals with factors
df[,numeric_cols] <- sapply(df[,numeric_cols], as.numeric)
return(df)
}
df<-makenumcols(df)
查看更多
明月照影归
4楼-- · 2019-01-01 06:59

To convert character to numeric you have to convert it into factor by applying

BankFinal1 <- transform(BankLoan,   LoanApproval=as.factor(LoanApproval))
BankFinal1 <- transform(BankFinal1, LoanApp=as.factor(LoanApproval))

You have to make two columns with the same data, because one column cannot convert into numeric. If you do one conversion it gives the below error

transform(BankData, LoanApp=as.numeric(LoanApproval))
Warning message:
  In eval(substitute(list(...)), `_data`, parent.frame()) :
  NAs introduced by coercion

so, after doing two column of the same data apply

BankFinal1 < transform(BankFinal1, LoanApp      = as.numeric(LoanApp), 
                                   LoanApproval = as.numeric(LoanApproval))

it will transform the character to numeric successfully

查看更多
临风纵饮
5楼-- · 2019-01-01 06:59

If the dataframe has multiple types of columns, some characters, some numeric try the following to convert just the columns that contain numeric values to numeric:

for (i in 1:length(data[1,])){
  if(length(as.numeric(data[,i][!is.na(data[,i])])[!is.na(as.numeric(data[,i][!is.na(data[,i])]))])==0){}
  else {
    data[,i]<-as.numeric(data[,i])
  }
}
查看更多
登录 后发表回答