김지영
김지영

Reputation: 359

Insert row based on Id in r

I got problems. Let me give you example.

x <- data.frame(id = letters[1:3], val0 = 1:3, val1 = 4:6, val2 = 7:9)
#   id val0 val1 val2
# 1  a    1    4    7
# 2  b    2    5    8
# 3  c    3    6    9
cbind(id = x[, 1], x[, -1]/rowSums(x[, -1]))
##   id       val0      val1      val2
## 1  a 0.08333333 0.3333333 0.5833333
## 2  b 0.13333333 0.3333333 0.5333333
## 3  c 0.16666667 0.3333333 0.5000000

My desired output is like below

#   id   val0      val1       val2
# 1  a    1         4          7
# 1  a 0.08333333 0.3333333 0.5833333
# 2  b    2         5          8
# 2  b 0.13333333 0.3333333 0.5333333
# 3  c    3         6          9
# 3  c 0.16666667 0.3333333 0.5000000

How can I do it??

Upvotes: 2

Views: 48

Answers (1)

akrun
akrun

Reputation: 887108

We can rbind the datasets and then do an order

library(data.table)
rbindlist(list(x, cbind(id = x[, 1], x[, -1]/rowSums(x[, -1]))))[order(id)]
#   id       val0      val1      val2
#1:  a 1.00000000 4.0000000 7.0000000
#2:  a 0.08333333 0.3333333 0.5833333
#3:  b 2.00000000 5.0000000 8.0000000
#4:  b 0.13333333 0.3333333 0.5333333
#5:  c 3.00000000 6.0000000 9.0000000
#6:  c 0.16666667 0.3333333 0.5000000

Upvotes: 1

Related Questions