【发布时间】:2014-07-08 01:11:25
【问题描述】:
我有一个变量df1$StudyAreaVisitNote,我把它变成了一个因子。但是,当我将df1 子集化为BS 时,这个变量不再是一个因素:对子集化数据使用 table() 函数会显示如果在原始数据上运行table() 似乎应该返回的结果数据?
为什么会这样?
我发现的两种解决方法是:
- 导出子集数据并重新导入
- 子集后,再次将列指定为因子
代码:
# My dataset can be found here: http://textuploader.com/9tx5 (I'm sure there's a better way to host it, but I'm new, sorry!)
# Load Initial Dataset (df1)
df1 <- read.csv("/Users/user/Desktop/untitled folder/pre_subset.csv", header=TRUE,sep=",")
# Make both columns factors
df1$Trap.Type <- factor(df1$Trap.Type)
df1$StudyAreaVisitNote <-factor(df1$StudyAreaVisitNote)
# Subset out site of interest
BS <- subset(df1, Trap.Type=="HR-BA-BS")
# Export to Excel, save as CSV after it's in excel
library(WriteXLS)
WriteXLS("BS", ExcelFileName = "/Users/user/Desktop/test.xlsx", col.names = TRUE, AdjWidth = TRUE, BoldHeaderRow = TRUE, FreezeRow = 1)
# Load second Dataset (df2)
df2 <- read.csv("/Users/user/Desktop/untitled folder/post_subset.csv", header=TRUE, sep=",")
# both datasets should be identical, and they are superficially, but...
# Have a look at df2
summary(df2$StudyAreaVisitNote) # Looks good, only counts levels that are present
# Now, look at BS from df1
summary(BS$StudyAreaVisitNote) # sessions not present in the subsetted data (but present in df1?) are included???
# Make BS$StudyAreaVisitNote a factor...Again??
BS$StudyAreaVisitNote <- factor(BS$StudyAreaVisitNote)
# Try line 31 again
summary(BS$StudyAreaVisitNote) # this time it works, why is factor not carried through during subset?
【问题讨论】:
-
我将您的问题重新命名为“为什么子集后未使用的因子水平没有下降?”。如果您的意思是“级别”,请不要说“字段”或“会话”。不要说“没有留下一个因素......奇怪的结果”,这并不能告诉我们任何事情。如果您想查看它是否仍然是一个因素,请使用
str()。作为奖励str()也告诉你它的水平。您会立即发现问题。 -
不要在第三方网站上发布指向您的数据集的链接(它现在 403 已过期),但即使没有,如果您使用
dput()并粘贴它会更清晰、更简单且自包含它进入问题。由于我们无法重现数据,我们无法重现您的代码;如果您为我们发布summary()/table()输出会更清楚。 -
"如果在原始数据上运行 table(),似乎应该返回什么奇怪的结果?" = "该表包含所有因素与原始级别相比,我希望删除子集中未使用的级别”。无论如何,您可以使用
tab <- table(...); tab[tab > 0]做到这一点 -
只是因为它有无关的水平,不要指责它不是一个因素:-)
-
“解决方法:导出并重新导入” 是一个红鲱鱼,只需使用
factor(..., levels=..., exclude=...)