我读了一个csv文件,如下所示
dataBU<-read.table("data1.csv",sep=",",header=T,stringsAsFactors=FALSE)
数据如下所示
id q1 q2 q3 q4
AB 1 1 0 1
AJ 0 2 3 0
AM 5 4 2 0
RA 2 1 10 0
BS 5 0 0 1
然后我想保留最后四列,因此我有
dataBu1<-dataBu[,2:5]
但是当我检查数据时,我找到了
> dataBu1[1,1]
[1] 1
> dataBu1[1,2]
[1] "1"
第一列和第二列属于不同类型。第一列是数字类型,第二列是字符类型。我假设它们都应该是数字类型。但事实证明,事实并非如此。导致这种情况的原因以及如何将第二列转换为数字类型。
答案 0 :(得分:0)
假设character
列中有numeric
个值,将其转换回numeric
的一种方法是使用as.numeric
set.seed(42)
dataBu1 <- data.frame(q1=sample(1:10,20,replace=TRUE),
q2=sample(c('', 5:15,'q2'),20,replace=TRUE), stringsAsFactors=FALSE)
as.numeric(dataBu1[,2]) #replace all the character values with NA but it issues a warning message
#[1] 14 5 15 15 NA 10 8 14 9 14 12 13 8 12 NA 13 NA 6 14 11
#Warning message:
#NAs introduced by coercion
表示多列(假设您使用stringsAsFactors=FALSE
读取数据集)
dataBu1[] <-lapply(dataBu1, as.numeric)
str(dataBu1)
#'data.frame': 20 obs. of 2 variables:
#$ q1: num 10 10 3 9 7 6 8 2 7 8 ...
#$ q2: num 15 5 NA NA 5 10 9 15 9 14 ...
或者没有收到警告信息
dataBu1[] <- lapply(dataBu1, function(x)
as.numeric(replace(x, !grepl("^[0-9]+$", x), NA)))
我猜你要求在使用read.table
读取非数字元素之后找到非数字元素的索引。
lapply(dataBu1, function(x) which(!grepl("^[0-9]+$", x)))
#$q1
#integer(0)
#$q2
#[1] 3 4 15 17