0

I have a dataframe:

df<-data.frame(Name=c('H001', 'H002', 'H003', 'H004', 'H005', 'H006',
                      'H007', 'H008', 'H009', 'H0010'),
               Room1=rnorm(10,0.4,0.5),
               Room2=rnorm(10,0.3,0.5),
               Room3=rnorm(10,0.7,0.5),
               Weight=sample(1:20,10))

I have multiplied each value of Name by its weighting factor (Weight) using:

weighted_df <- data.frame(df[rep(seq_len(dim(df)[1]), df$Weight), c(1,2,3,4), drop = FALSE], row.names=NULL)

But I want to add a 5th column ID, so that each row can be identified with a unique Name and ID combination. The resulting df should look like;

     name      Room1      Room2     Room3 ID 
1    H001  0.4390566  0.7158113 0.7400785 1
2    H001  0.4390566  0.7158113 0.7400785 2
3    H001  0.4390566  0.7158113 0.7400785 3
4    H001  0.4390566  0.7158113 0.7400785 4
5    H001  0.4390566  0.7158113 0.7400785 5
6    H001  0.4390566  0.7158113 0.7400785 6
7    H001  0.4390566  0.7158113 0.7400785 7
8    H001  0.4390566  0.7158113 0.7400785 8
9    H001  0.4390566  0.7158113 0.7400785 9
10   H001  0.4390566  0.7158113 0.7400785 10
11   H001  0.4390566  0.7158113 0.7400785 11
12   H001  0.4390566  0.7158113 0.7400785 12
13   H001  0.4390566  0.7158113 0.7400785 13
14   H001  0.4390566  0.7158113 0.7400785 14
15   H001  0.4390566  0.7158113 0.7400785 15
16   H001  0.4390566  0.7158113 0.7400785 16
17   H001  0.4390566  0.7158113 0.7400785 17
18   H002  0.4041108 -0.1668988 0.6594539 1
19   H002  0.4041108 -0.1668988 0.6594539 2
20   H002  0.4041108 -0.1668988 0.6594539 3

Thanks in advance.

Loz
  • 137
  • 8

1 Answers1

1

It can be done using rowid

library(data.table)
library(dplyr)
weighted_df %>% 
   mutate(ID = rowid(Name))

-output

#     Name        Room1       Room2        Room3 ID
#1    H001  0.579649851  0.84602529  0.620850211  1
#2    H001  0.579649851  0.84602529  0.620850211  2
#3    H001  0.579649851  0.84602529  0.620850211  3
#4    H001  0.579649851  0.84602529  0.620850211  4
#5    H001  0.579649851  0.84602529  0.620850211  5
#6    H001  0.579649851  0.84602529  0.620850211  6
#7    H001  0.579649851  0.84602529  0.620850211  7
#8    H001  0.579649851  0.84602529  0.620850211  8
#9    H001  0.579649851  0.84602529  0.620850211  9
#10   H001  0.579649851  0.84602529  0.620850211 10
#11   H001  0.579649851  0.84602529  0.620850211 11
#12   H001  0.579649851  0.84602529  0.620850211 12
#13   H001  0.579649851  0.84602529  0.620850211 13
#14   H001  0.579649851  0.84602529  0.620850211 14
#15   H001  0.579649851  0.84602529  0.620850211 15
#16   H001  0.579649851  0.84602529  0.620850211 16
#17   H001  0.579649851  0.84602529  0.620850211 17
#18   H002  1.457267473 -1.18612874  0.553957293  1
#19   H002  1.457267473 -1.18612874  0.553957293  2
# ...
akrun
  • 874,273
  • 37
  • 540
  • 662