4

単語と数値エントリを含むデータ フレームがあります。単語 now の行エントリが同一であるすべてのエントリを合計したいと思います。

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(head(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

助けてくれてありがとう!

4

1 に答える 1

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

出生率を合計するのは良い考えですか?

実際のデータを使用するとddply、 fromを使用しplyrて同様の方法で集計する方が便利な場合があります (ただし、2 つの異なる列sumで andを使用する必要があります)。mean

require( plyr )
ddply( mydata , "District" , function(df) c( "Pop" = sum( df$Population), "Robbery" = mean( df$Robbery ) ) )
#  District    Pop    Crime
#1    Mitte 333152 183.6667
于 2013-05-01T12:37:49.863 に答える