将带有“ NULL”的列转换为数字价值观 [英] Transform to numeric a column with "NULL" values

查看:98
本文介绍了将带有“ NULL”的列转换为数字价值观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将数据集导入到R中,其中应该在其中包含数字的列中存在 NULL 。这使R将列类设置为字符 factor ,这取决于您是否使用 stringAsFactors 参数。

I've imported a dataset into R where in a column which should be supposed to contain numeric values are present NULL. This make R set the column class to character or factor depending on if you are using or not the stringAsFactors argument.

这是数据集的结构。

> str(data)
'data.frame':   1016 obs. of  10 variables:
 $ Date       : Date, format: "2014-01-01" "2014-01-01" "2014-01-01" "2014-01-01" ...
 $ Name       : chr  "Chi" "Chi" "Chi" "Chi" ...
 $ Impressions: chr  "229097" "3323" "70171" "1359" ...
 $ Revenue    : num  533.78 11.62 346.16 3.36 1282.28 ...
 $ Clicks     : num  472 13 369 1 963 161 1 7 317 21 ...
 $ CTR        : chr  "0.21" "0.39" "0.53" "0.07" ...
 $ PCC        : chr  "32" "2" "18" "0" ...
 $ PCOV       : chr  "3470.52" "94.97" "2176.95" "0" ...
 $ PCROI      : chr  "6.5" "8.17" "6.29" "NULL" ...
 $ Dimension  : Factor w/ 11 levels "100x72","1200x627",..: 1 3 4 5 7 8 9 10 11 1 ...

我想将PCROI列转换为数字,但包含 NULL s使其更难。
我试图解决将值 0 设置为当前值为 NULL ,但出现以下错误消息:

I would like to transform the PCROI column as numeric, but containing NULLs it makes this harder. I've tried to get around the issue setting the value 0 to all observations where current value is NULL, but I got the following error message:

> data$PCROI[which(data$PCROI == "NULL"), ] <- 0
Error in data$PCROI[which(data$PCROI == "NULL"), ] <- 0 : 
  incorrect number of subscripts on matrix

下标的数目不正确我的想法是更改为 0 所有 NULL 观察值,然后使用 as.numeric 函数。

My idea was to change to 0 all the NULL observations and afterwards transform all the column to numeric using the as.numeric function.

推荐答案

您遇到语法错误:

data$PCROI[which(data$PCROI == "NULL"), ] <- 0 # will not work
data$PCROI[which(data$PCROI == "NULL")] <- 0 # will work



by the way you can say:

data$PCROI = as.numeric(data$PCROI)

它将自动将您的 NULL转换为NA。

it will convert your "NULL" to NA automatically.

这篇关于将带有“ NULL”的列转换为数字价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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