Levels in R Dataframe

旧街凉风 提交于 2019-12-01 17:42:07

When you read in the data with read.table (or read.csv? - you didn't specify), add the argument stringsAsFactors = FALSE. Then you will get character data instead.

If you are expecting integers for the column then you must have data that is not interpretable as integers, so convert to numeric after you've read it.

txt <- c("x,y,z", "1,2,3", "a,b,c")

d <- read.csv(textConnection(txt))
sapply(d, class)
       x        y        z 
##"factor" "factor" "factor" 

## we don't want factors, but characters
d <- read.csv(textConnection(txt), stringsAsFactors = FALSE)
sapply(d, class)

#          x           y           z 
#"character" "character" "character" 

## convert x to numeric, and wear NAs for non numeric data
as.numeric(d$x)

#[1]  1 NA
#Warning message:
#NAs introduced by coercion 

Finally, if you want to ignore these input details and extract the integer levels from the factor use e.g. as.numeric(levels(d$x))[d$x], as per "Warning" in ?factor.

Arthur

or you can simply use

d$x2 = as.numeric(as.character(d$x)).

Working from your clarification I suggest you redo your read statement with read.table and header=TRUE, stringAsFactors=FALSE and as.is = !stringsAsFactors and sep=",":

datinp <- read.table("Rdata.csv", header=TRUE, stringAsFactors=FALSE , 
                       as.is = !stringsAsFactors , sep=",") 
datinp$a <- as.numeric(datinp$a)
datinp$b <- as.numeric(datinp$b)
datinp$ctr <- with(datinp, as.integer(a/b) ) # no loop needed when using vector arithmetic

Do summary(data) to check things got read in properly. If columns aren't numeric that should be, look at the colClasses argument to read.csv to force it, which will probably also result in NA values for poorly-formed numbers.

help(read.csv) will help.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!