我有R中的以下數據幀:的R - 計數在多個列指標(如在Excel SUMPRODUCT)
df <- data.frame(id=c('a','b','a','c','b','a'),
indicator1=c(1,0,0,0,1,1),
indicator2=c(0,0,0,1,0,1),
extra1=c(4,5,12,4,3,7),
extra2=c('z','z','x','y','x','x'))
id indicator1 indicator2 extra1 extra2
a 1 0 4 z
b 0 0 5 z
a 0 0 12 x
c 0 1 4 y
b 1 0 3 x
a 1 1 7 x
我想與計數超過的數目的所有行添加新列這個特定的id出現的各種指標等於1.例如:
id indicator1 indicator2 extra1 extra2 countInd1 countInd2 countInd1Ind2
a 1 0 4 z 2 1 1
b 0 0 5 z 1 0 0
a 0 0 12 x 2 1 1
c 0 1 4 y 0 1 0
b 1 0 3 x 1 0 0
a 1 1 7 x 2 1 1
我該怎麼做?
如果'indicator1'和'indicator2'是(因爲他們似乎,似乎被命名)的指標,'DT [ ,c('ind1','ind2','ind1ind2'):= list(sum(indicator1),sum(indicator2),sum((indicator1 + indicator2)> 1)),by = id]'should work(and效率更高) – mnel
@mnel,這是我想到的,但我並不想對「indicator1」和「indicator2」列中是否有其他值做任何假設。 – A5C1D2H2I1M1N2O1R2T1