【问题标题】:R subsetting a data frame based on a factor variable formatted like a range (xx-xx)R基于格式为范围(xx-xx)的因子变量对数据框进行子集
【发布时间】:2013-03-21 13:56:43
【问题描述】:

我现在面临这个问题好几个小时了,但我知道我遗漏了一些明显的东西。

这是我的问题:

我在 .xlsx 文件中有一个数据框,可以下载here。

我在 MAC 上使用 RStudio 将此数据帧加载到 R 中,并将其命名为 demoData。 有 5 个变量(AgeRange、Women、Men、Total 和 Year)。

我无法使用 AgeRange 上的条件对该数据框进行子集化。该变量的格式如下:xx-xx(00-04 表示 00 到 04 岁之间的人)。当我尝试这样做时,我得到的消息是没有行满足这个条件。 变量“AgeRange”的类是因子。

这是我的代码:

demoData[demoData$AgeRange=="00-04",]

感谢您的帮助。

编辑:来自 Arun。这是head(demoData)的输入:

     Age Feminin Masculin. Ensemble Annee
1 00-04     720       745     1465  2004 
2 05-09     745       767     1512  2004 
3 10-14     813       830     1643  2004 
4 15-19     824       820     1644  2004 
5 20-24     839       823     1662  2004 
6 25-29     752       699     1450  2004 

# str(demoData)
'data.frame':   272 obs. of  5 variables:
 $ Age      : Factor w/ 16 levels "00-04 ","05-09 ",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ Feminin  : Factor w/ 216 levels "138 ","139 ",..: 112 124 164 165 174 130 106 86 78 66 ...
 $ Masculin.: Factor w/ 201 levels "120 ","122 ",..: 132 141 174 169 170 124 111 89 90 75 ...
 $ Ensemble : Factor w/ 242 levels "1041 ","1044 ",..: 53 66 115 116 119 50 38 14 9 238 ...
 $ Annee    : Factor w/ 17 levels "2004 ","2005",..: 1 1 1 1 1 1 1 1 1 1 ...

【问题讨论】:

  • 请使用dput(head(demoData)) 提供您的数据子集。将xlsx 文件加载到 R 中可能会很痛苦。
  • 你的变量叫Age,而不是AgeRange ?
  • “00-04”后面有一个空格。那就是问题所在。试试demoData[demoData$Age == "00-04 "]
  • 你能告诉我summary( demoData )吗?
  • @Arun 哦,对了 - 数据链接已发布。当然!我以为你有某种神奇的方法来确定空格与空格的界限!!!

标签: r dataframe subset r-factor


【解决方案1】:

我使用 xlsx 包读取了您的 xlsx 文件:

df<-read.xlsx("C:/Users/swatson1/Downloads/Evolution_Population_2004_2020.xlsx",1)

它看起来像这样:

> df
        Age Feminin MasculinÂ. Ensemble  Annee
1   00-04Â    720Â       745Â    1465Â  2004Â 
2   05-09Â    745Â       767Â    1512Â  2004Â 

你可以替换每一列,去掉多余的字符,比如:

df$Age<-substr(df$Age,1,5)

或者,使用gsub,因为无论条目的长度如何,这都适用于任何列:

df$Age<-gsub("Â\\s","",df$Age)

那么你的代码就可以工作了:

df[df$Age=="00-04",]

【讨论】:

  • (+1) 最好删除最后一个字符而不是说 1:5,因为还有年龄值,例如:75 &amp;+。
  • 同意,我认为gsub 在这种情况下会更有用 - 将进行编辑。
  • 我终于用下面的代码解决了问题:x&lt;-gsub("\xC2\xA0","",x)
【解决方案2】:
#coppied from the Excel file 
str1 <- "00-04 "
utf8ToInt(str1)
#[1]  48  48  45  48  52 160

字符串末尾似乎有一个不间断的空格。清理您的文件。

您应该能够使用

删除不间断空格
df$Age <- gsub(intToUtf8(160),"",df$Age)

【讨论】:

  • 您好,感谢您的回答。但是我仍然无法删除数据框中的不间断空格。假设我只想删除不间断空格(我在文件中看不到 Â),我应该怎么做?我尝试在 Excel 中使用 Substitute 函数处理这个问题,但我无法将数据用作“值”与公式。谢谢您的帮助。这个不间断的空间让我抓狂:)
  • 查看编辑。但是,我无法在您的数据上测试解决方案,因为我不会将 Excel 文件直接读入 R。我总是从 CSV 文件中读取数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-04
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多