2013-05-01 44 views
4

我有一个包含单词和数字条目的数据框。我想总结现在单词中的行条目是相同的所有条目。R数据框中的条件总和取决于列中的字

District name Population Child birth rate 
A    30,000  .7 
A    20,000  .5 
B    10,000  .09 
B    15,000  .6 
C    80,000  .007 

我想概括一下区级的人口和儿童出生率。 我试着用lapply和sum,但我想不出来。

的结果dput(头(MYDATA)是:

structure(list(District = structure(c(5L, 5L, 5L, 5L, 5L, 5L), .Label =   c("Charlottenburg-Wilmersdorf", 
"Friedrichshain-Kreuzberg", "Lichtenberg", "Marzahn-Hellersdorf", 
"Mitte", "Neukoelln", "Pankow", "Reinickendorf", "Spandau", "Steglitz-Zehlendorf", 
"Tempelhof-Schoeneberg", "Treptow-Koepenick"), class = "factor"), 
Population = c(81205L, 70911L, 5629L, 12328L, 78290L, 84789L 
), Overall.crime = c(27864L, 13181L, 943L, 4515L, 15673L, 
16350L), Robbery = c(315L, 195L, 20L, 79L, 232L, 261L), Mugging = c(183L, 
81L, 9L, 54L, 111L, 118L), Assault = c(2016L, 1046L, 51L, 
468L, 1679L, 1718L), Molestation.Stalking = c(480L, 429L, 
16L, 114L, 567L, 601L), Theft = c(13587L, 4961L, 396L, 2019L, 
6725L, 6954L), Car.Theft = c(185L, 149L, 10L, 28L, 159L, 
159L), Bycicle.Theft = c(1444L, 561L, 95L, 123L, 588L, 595L 
), Burglary = c(557L, 297L, 37L, 87L, 397L, 528L), Arson = c(36L, 
51L, 7L, 15L, 28L, 56L), Property.Damage = c(2113L, 871L, 
64L, 260L, 1257L, 1172L), Drug.Offenses = c(781L, 538L, 24L, 
87L, 604L, 492L)), .Names = c("District", "Population", "Overall.crime", 
"Robbery", "Mugging", "Assault", "Molestation.Stalking", "Theft", 
"Car.Theft", "Bycicle.Theft", "Burglary", "Arson", "Property.Damage", 
"Drug.Offenses"), row.names = c(NA, 6L), class = "data.frame") 

我之前所有的德国名字就饶了你,但我想这是愚蠢的,因为这个问题是数据中...

使用ddply给了我以下错误:

Error in df$Population : object of type 'closure' is not subsettable 

感谢您的帮助

+0

请张贴代码您正在使用运行'ddply'命令。我所做的只是复制上面的数据结构,并像这样分配'mydata < - ...',我只需点击'ctrl-v'来代替'...'来粘贴上面的数据结构。然后运行下面输入的* exact * same'ddply'命令。请确认你是否在做同样的事情? – 2013-05-01 13:14:46

回答

4

使用您最初发布的数据是否意味着要这样做?

df <- read.table(text = "District_name Population Child_birth_rate 
A    30000  .7 
A    20000  .5 
B    10000  .09 
B    15000  .6 
C    80000  .007" , h = TRUE) 

aggregate(cbind(Population , Child_birth_rate) ~ District_name , data = df , sum) 
# District_name Population Child_birth_rate 
#1    A  50000   1.200 
#2    B  25000   0.690 
#3    C  80000   0.007 

这是个好主意,总和出生率?

使用实际数据可能是使用ddplyplyr在一个呈三角时尚聚集更方便(但要在两个不同的列使用summean):

require(plyr) 
ddply(mydata , "District" , function(df) c("Pop" = sum(df$Population), "Robbery" = mean(df$Robbery))) 
# District Pop Crime 
#1 Mitte 333152 183.6667 
+0

是的,SimonO101!但是,我得到一个错误报告: 不能强制类“”公式“”到一个data.frame 我已经尝试使数据帧矩阵,并再次做到这一点;它仍然报告相同的错误。 – PikkuKatja 2013-05-01 12:44:25

+0

而且,嘿嘿,这个出生率实际上不应该总结,而是平均的。我用“意思”来代替“sum”,不是吗? – PikkuKatja 2013-05-01 12:46:59

+0

我添加了dput(head(mydata)),并希望你不会太在意所有这些德国人的名字;-)它有任何帮助吗? – PikkuKatja 2013-05-01 13:00:31