How to get frequencies then add it as a variable in an array?

前端 未结 3 1224
天命终不由人
天命终不由人 2021-01-12 18:33

Let\'s say I have an array of this format

X  Y  Z
A  1  0
A  2  1
B  1  1
B  2  1
B  1  0

I want to find the frequency of X and the frequen

3条回答
  •  Happy的楠姐
    2021-01-12 18:42

    Here's a data.table way:

    require(data.table)
    DT <- data.table(dat)
    DT[,nx:=.N,by=X][,nxy:=.N,by=list(X,Y)]
    

    That last step created the two columns:

    DT
    #    X Y Z nx nxy
    # 1: A 1 0  2   1
    # 2: A 2 1  2   1
    # 3: B 1 1  3   2
    # 4: B 2 1  3   1
    # 5: B 1 0  3   2
    

    And it could have been written in two lines instead of one:

    DT[,nx:=.N,by=X]
    DT[,nxy:=.N,by=list(X,Y)]
    

提交回复
热议问题