2

I'm working in R.

I have a dataframe df with three columns. The structure looks like this:

df <- data.frame(c(11:15,4:7,21:24), c(rep("A",9),rep("B",4)), c(rep("X",5),rep("Y",4),rep("X",4)))
colnames(df) <- c("pos","name","name2")

Example:

pos   name   name2
11    A      X 
12    A      X
13    A      X
14    A      X
15    A      X
4     A      Y
5     A      Y
6     A      Y
7     A      Y
21    B      X
22    B      X
23    B      X
24    B      X

From this dataframe, I want to create a new one (df_new) that looks like this

name    name2   pos_min   pos_max
A       X       11        15
A       Y       4         7
B       X       21        24

So for every unique combination of name & name2 (in this case: A-X, A-Y and B-X), I want to put the minimal and maximal value of df$pos in two new columns.

Can anybody help me to achieve this?

Florian
  • 24,425
  • 4
  • 49
  • 80
user1987607
  • 2,057
  • 6
  • 26
  • 53

1 Answers1

4

This can be solved using the dplyr package:

df_new <- df %>%
          group_by(name, name2) %>%
          summarise(pos_min = min(pos),
                    pos_max = max(pos))
akash87
  • 3,876
  • 3
  • 14
  • 30