从字符转换为数字数据帧 [英] Converting from a character to a numeric data frame

查看:361
本文介绍了从字符转换为数字数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个字符数据框,其中有 NaN 。我需要删除具有 NaN 的任何行,然后将其转换为数字数据框。



如果我只是在数据框上做as.numeric,我碰到以下

 错误:(list)对象不能强制输入' double'
1:
0:


解决方案

由于@thijs van den bergh指向,

  dat<  -  data.frame(x = c( NaN,2),y = c(NaN,3),stringsAsFactors = FALSE)

dat< - as.data.frame(sapply(dat,as.numeric ))#< - sapply在这里

dat [complete.cases(dat),]
#xy
#2 2 3

一种的方法。



您的错误来自尝试使 data.frame 数字。显示的 sapply 选项是使每列列向量数值。


I have a character data frame in R which has NaNs in it. I need to remove any row with a NaN and then convert it to a numeric data frame.

If I just do as.numeric on the data frame, I run into the following

Error: (list) object cannot be coerced to type 'double'
 1:
 0:

解决方案

As @thijs van den bergh points you to,

dat <- data.frame(x=c("NaN","2"),y=c("NaN","3"),stringsAsFactors=FALSE)

dat <- as.data.frame(sapply(dat, as.numeric)) #<- sapply is here

dat[complete.cases(dat), ]
#  x y
#2 2 3

Is one way to do this.

Your error comes from trying to make a data.frame numeric. The sapply option I show is instead making each column vector numeric.

这篇关于从字符转换为数字数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆