簡體   English   中英

如何根據R中的兩個不同列添加行的值?

[英]How to add values of rows depending on two different columns in R?

如何在R中編寫代碼以為兩個不同變量的所有相同組成添加一個變量的值? 例如,我要添加cd的所有流行音樂:403縣:4017 /和cd的所有流行音樂:406和縣:4017。

cd  county  pop
403 4017    1474
403 4017    0
403 4017    869
403 4017    393
403 4017    773
403 4017    1108
403 4017    929
403 4017    730
403 4017    0
406 4017    0
406 4017    2982
406 4017    1254
406 4017    752
406 4017    153
406 4017    0
406 4017    0
406 4017    3775
406 4017    0
406 4017    777
406 4017    5923

有關此主題的問題是否已經回答。 我應該使用什么關鍵字來搜索它?

提前致謝!

require(plyr)
ddply(df,.(cd,county),summarize,total=sum(pop))

   cd county total
1 403   4017  6276
2 406   4017 15616

@Troy給出的答案可能是大多數R用戶會告訴您的內容(即使用plyrddply()

但是,由於我第一次接觸數據分析是通過數據庫腳本編寫的,因此我仍然不sqldf軟件包來執行這些任務。

我還發現SQL對非R用戶更加透明(在我從事大部分工作的社會科學社區中經常遇到這種情況)。

這是使用sqldf產生相同輸出的問題的解決方案:

#your data assigned to dat
pop <- c(1474,0,869,393,773,1108,929,730,0
        ,0,2982,1254,752,153,0,0,3775,0
        ,777,5923)  
cd <- c(rep(403, 9), rep(406, 11))
county <- rep(4017, 20)

dat <- as.data.frame(cbind(cd, county, pop))

#load sqldf
require(sqldf)

#write a simple SQL aggregate query
#i.e. "select" your fields specifying the aggregate function for the 
#relevant field, "from" a table called dat, and "group by" cd and county
sqldf('select
        cd
        ,county
        ,sum(pop) as total
      from dat
      group by 
        cd
        ,county')

   cd county total
1 403   4017  6276
2 406   4017 15616

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM