R Dataframe 中的级别
我从 .csv 文件导入数据,并附加数据集。
我的问题:一个变量是整数形式,有 295 个级别。我需要使用这个变量来创建其他变量,但我不知道如何处理这些级别。
这些是什么?我该如何处理它们?
I imported data from a .csv file, and attached the dataset.
My problem: one variable is in integer form and has 295 levels. I need to use this variable to create others, but I don't know how to deal with the levels.
What are these, and how do I deal with them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
进行摘要(数据)以检查是否正确读取内容。如果列不是应该是数字的,请查看 read.csv 的 colClasses 参数来强制它,这也可能会导致格式不良的数字产生 NA 值。
help(read.csv) 会有所帮助。
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.
根据您的澄清,我建议您使用 read.table 和 header=TRUE、stringAsFactors=FALSE 和 as.is = !stringsAsFactors 和 sep="," 重做读取语句:
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=",":
或者您可以简单地使用
d$x2 = as.numeric(as.character(d$x))
。or you can simply use
d$x2 = as.numeric(as.character(d$x))
.当您使用 read.table (或 read.csv? - 您没有指定)读取数据时,请添加参数 stringsAsFactors = FALSE。然后你将获得字符数据。
如果您期望该列为整数,那么您必须拥有无法解释为整数的数据,因此在读取后将其转换为数字。
最后,如果您想忽略这些输入详细信息并从因子中提取整数级别,请使用例如 as.numeric(levels(d$x))[d$x],按照 ?factor 中的“警告”。
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.
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.