Reputation: 3
I have a data frame and I want to create another column based on the information of three different columns. I am using R.
I want to start counting on 0 and to add 2 in each new cell, based on a column Time and on Item and Participants information. I want to have 0 for the beginning of the Time counting (which is in ms) for each item of each participant.
df <- data.frame(Item=c(1,1,1,1,1,1,2,2,2,2,2,2),
Part=c(1,1,1,2,2,2,1,1,1,2,2,2),
Time=c(1234,1235,1236,345,346,347,1546,1547,1548,234,235,236))
Item Part Time
1 1 1 1234
2 1 1 1235
3 1 1 1236
4 1 2 345
5 1 2 346
6 1 2 347
7 2 1 1546
8 2 1 1547
9 2 1 1548
10 2 2 234
11 2 2 235
12 2 2 236
With the new column the table would be something like:
Item Part Time NewColumn
1 1 1 1234 0
2 1 1 1235 2
3 1 1 1236 4
4 1 2 345 0
5 1 2 346 2
6 1 2 347 4
7 2 1 1546 0
8 2 1 1547 2
9 2 1 1548 4
10 2 2 234 0
11 2 2 235 2
12 2 2 236 4
Many thanks in advance.
Upvotes: 0
Views: 527
Reputation: 10913
+1 for library(plyr)
library(plyr)
ddply(df, c("Item","Part"), mutate,NewColumn = seq(0,4,2))
Item Part Time NewColumn
1 1 1234 0
1 1 1235 2
1 1 1236 4
1 2 345 0
1 2 346 2
1 2 347 4
2 1 1546 0
2 1 1547 2
2 1 1548 4
2 2 234 0
2 2 235 2
2 2 236 4
Upvotes: 1
Reputation: 2989
In case the structure stays as it is
library(dplyr)
result <- df %>% group_by(Part, Item) %>% mutate(NewColumn = seq (0,4,2))
I group by Item
and Part
and create a new column that counts 0, 2, 4
Item Part Time NewColumn
1 1 1 1234 0
2 1 1 1235 2
3 1 1 1236 4
4 1 2 345 0
5 1 2 346 2
6 1 2 347 4
7 2 1 1546 0
8 2 1 1547 2
9 2 1 1548 4
10 2 2 234 0
11 2 2 235 2
12 2 2 236 4
In order to be more flexible (if you have more than 3 rows per group), you can use
result <- df %>% group_by(Part, Item) %>% mutate(NewColumn = 2* (row_number()-1))
which will will generate numbers in the sequence 0, 2, 4, 6, 8,...
Upvotes: 4
Reputation: 28309
library(data.table)
df <- data.table(df)
df[, NewCol := seq(0,nrow(df),2), by=list(Item,Part)]
Upvotes: 2