簡體   English   中英

R:匯總相似的列,並使用列名稱作為R中的值

[英]R: aggregate similar columns and use column name as value in R

我有一個看起來像這樣的數據框

ID  FactorA FactorB Industry1 Industry2  Curr1   Curr2
1   1.121   0.121   1         0          1       0
2   1.52    0.114   0         1          1       0

因子A和因子B是實數,並且都具有值。 然而Industry1industry2 (相同貨幣1和貨幣2)是二進制的,即,僅它們中的一個可以具有value=1

由於我想縮小數據以用於存儲,因為我有80種行業類型和100種貨幣類型,並且其中只有一種具有值,所以我想像這樣存儲它們

ID  FactorA FactorB Industry    Curr
1   1.121   0.121   Industry1   Curr1   
2   1.52    0.114   Industry2   Curr1

基本上,我想使用值為1的列名稱,並連接所有type=IndustryCurr等的字符串。我確實有另一個表將每個列名稱鏈接到其類型

ColName     Type
FactorA     Factor
FactorB     Factor
Industry1   Industry
Industry2   Industry
Curr1       Curr
Curr2       Curr

您可以使用reshape2包中的melt函數折疊列。 如評論中所述,提供一個示例-使生活更輕松:

dd = data.frame(ID = 1:2, factorA = c(1.121, 1.52),
  factorB = c(0.12, 0.114), Ind1 = 1:0, Ind2= 0:1,
  Curr1 = 1, Curr2=0)

首先加載包:

library(reshape2)

接下來melt列,但保護前三個列:

dd1 = melt(dd, id=1:3)

查看melt幫助文件以獲取更多信息。 然后只需進行一些子設置即可獲得所需的內容:

dd2 = dd1[dd1$value == 1,]

您可能需要刪除最后一列。

您可以使用ifelse創建新列:

mydata$Industry = ifelse(mydata$Industry1, "Industry1", "Industry2")
mydata$Curr = ifelse(mydata$Curr1, "Curr1", "Curr2")

暫無
暫無

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

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