我从 .csv 文件导入数据,并附加数据集。
我的问题:一个变量是整数形式,有 295 个级别。我需要使用这个变量来创建其他变量,但我不知道如何处理这些级别。
这些是什么?我该如何处理它们?
当您使用 read.table (或 read.csv? - 您没有指定)读取数据时,添加参数 stringsAsFactors = FALSE。然后你将获得字符数据。
如果您希望该列为整数,那么您必须拥有无法解释为整数的数据,因此在读取后将其转换为数字。
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
最后,如果您想忽略这些输入详细信息并从因子中提取整数级别,请使用例如as.numeric(levels(d$x))[d$x],根据 ?factor 中的“警告”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)