在数据分析中,我们经常面对不合适的数据,因此数据分析变得困难。不适当数据的一个示例是通过将缺失值命名为“缺失”或“不可用”来读取缺失值。可以通过使用以下语法来完成-
levels(“data_frame_name”$”Column_name”)[levels(“data_frame_name”$”Column_name”=="Missing"]<-NA
请看以下数据帧-
Class<-as.factor(sample(c("First","Second","Missing"),20,replace=TRUE)) Score<-sample(1:10,20,replace=TRUE) df1<-data.frame(Class,Score) df1
输出结果
Class Score 1 Missing 2 2 First 2 3 Second 5 4 First 2 5 Missing 9 6 Second 3 7 Missing 7 8 Missing 3 9 First 3 10 Second 5 11 First 5 12 Second 5 13 Missing 1 14 First 2 15 Second 2 16 Second 3 17 Second 3 18 Second 9 19 Second 10 20 Missing 1
将数据帧df1中Class的缺失值更改为NA-
levels(df1$Class)[levels(df1$Class)=="Missing"]<-NA df1
输出结果
Class Score 1 <NA> 4 2 Second 4 3 <NA> 4 4 <NA> 8 5 First 3 6 Second 1 7 <NA> 5 8 First 10 9 Second 8 10 <NA> 5 11 First 4 12 Second 5 13 First 2 14 <NA> 4 15 <NA> 3 16 First 4 17 <NA> 9 18 First 4 19 First 8 20 Second 7
让我们看另一个例子-
Grp<-as.factor(sample(c("A","B","Not Available"),20,replace=TRUE)) Age<-sample(21:50,20) df2<-data.frame(Grp,Age) df2
输出结果
Grp Age 1 A 37 2 B 49 3 Not Available 31 4 B 34 5 B 46 6 Not Available 26 7 A 27 8 A 25 9 A 32 10 B 28 11 A 47 12 A 30 13 Not Available 38 14 B 39 15 A 33 16 Not Available 42 17 B 35 18 Not Available 21 19 Not Available 36 20 A 24
将数据帧df2中Grp的Not Available值更改为NA-
levels(df2$Grp)[levels(df2$Grp)=="Not Available"]<NA df2
输出结果
Grp Age 1 <NA> 32 2 <NA> 35 3 A 23 4 B 26 5 A 44 6 B 47 7 A 37 8 A 36 9 A 41 10 B 25 11 <NA> 45 12 A 42 13 <NA> 28 14 A 21 15 <NA> 48 16 A 38 17 <NA> 50 18 A 33 19 A 27 20 <NA> 22