【发布时间】:2020-05-23 01:47:45
【问题描述】:
我目前正在处理data.frame 中的分类数据,其中两列是类型因子。它总共有大约 9000 行,有 40 多个级别。目前,我首先将这些列更改为字符,因为当我尝试使用它们的因子形式更改它们时,我得到了 NA 值。将这些列更改为字符后,我能够更改它们,然后将列的类型更改回因子。
这是我的方法代码:
library(dplyr)
#model data frame
df <- data.frame(A= as.factor(c("Jerry", "Kelly","Kelly", "Lion", "Zebra", "Bear", "Kelly")),
B= as.factor(c("Eats", "Jumps", "Roasts", "Roars", "Runs", "Sleeps", "Jumps")))
glimpse(df)
#Observations: 7
#Variables: 2
#$ A <fct> Jerry, Kelly, Kelly, Lion, Zebra, Bear, Kelly
#$ B <fct> Eats, Jumps, Roasts, Roars, Runs, Sleeps, Jumps
#select those factor columns and change their type
df[c("A","B")] <- lapply(df[ c("A", "B")], as.character)
glimpse(df)
#Variables: 2
#$ A <chr> "Jerry", "Kelly", "Kelly", "Lion", "Zebra", "Bear", "K...
#$ B <chr> "Eats", "Jumps", "Roasts", "Roars", "Runs", "Sleeps", ...
#now I want to change Kelly's actions for example
df<- within(df,B[A %in% c("Kelly")] <- "CHANGED")
print(df)
# A B
#1 Jerry Eats
#2 Kelly CHANGED
#3 Kelly CHANGED
#4 Lion Roars
#5 Zebra Runs
#6 Bear Sleeps
#7 Kelly CHANGED
#Then I change it back
df[c("A","B")] <- lapply(df[ c("A", "B")], as.factor)
glimpse(df)
#Observations: 7
#Variables: 2
#$ A <fct> Jerry, Kelly, Kelly, Lion, Zebra, Bear, Kelly
#$ B <fct> Eats, CHANGED, CHANGED, Roars, Runs, Sleeps, CHANGED
问题是,从我正在使用的数据来看,字符方式方法不是一个好方法。有没有一种替代方法可以让我以一种简洁的方式将因子/水平转换为因子/水平?用独特的功能测试,使字符列表现得像关卡,但我确信我缺少一些知识。
【问题讨论】:
-
作为替代,为什么不将它们作为字符读入然后更新它们,以便您只需将它们设置为因子一次
-
感谢您的回复。我正在处理别人的脚本文件。所以我不知道我是否应该去那里更改他的代码。我的任务是分类,以及完成数据加载和清理的部分。
-
还不错;但您可以将
stringsAsFactors=FALSE添加到数据加载部分 -
是的,你绝对正确。让我再深入研究一下他的代码,我不想在我这样做之后搞砸一些事情。你知道,我告诉那个**就这样做,但他不听。
标签: r dataframe data-cleaning