0

I have a dataset with 8588 rows and 91 columns. I want to divide it into two new data frames but based on predetermined row numbers.

Example

First data frame

1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J

The second data frame contains the row number

4
7
5
1
9

The third data frame contains the row number

6
10
2
3
8

the result is like this

1st new data frame

4 D
7 G
5 E
1 A
9 I

2nd new data frame

6 F
10 J
2 B
3 C
8 H

The question is how to do this? Thank you

dikfaj
  • 1
  • 2
  • `df1 <- subset(df, V1 %in% c(4,7, 5,1,9))` and `df2 <- subset(df, V1 %in% c(6,10, 2,3,8))` where `V1` is the column name. – Ronak Shah Apr 06 '20 at 07:08
  • Yes its work but But the result is not random only sequentially. For df1 is 1 4 5 7 9 not 4, 7, 5, 1, 9. – dikfaj Apr 06 '20 at 08:22

1 Answers1

0

We can subset the dataframe based on values and then match and order.

df1 <- subset(df, V1 %in% c(4,7, 5,1,9))
df2 <- subset(df, V1 %in% c(6,10, 2,3,8))

df1 <- df1[order(match(df1$V1, c(4,7, 5,1,9))), ]
df1
#  V1 V2
#4  4  D
#7  7  G
#5  5  E
#1  1  A
#9  9  I

df2 <- df2[order(match(df2$V1, c(6,10, 2,3,8))), ]
df2
#   V1 V2
#6   6  F
#10 10  J
#2   2  B
#3   3  C
#8   8  H
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213