0

Suppose i have dataset

df=structure(list(SaleCount = c(7L, 35L, 340L, 260L, 3L, 31L, 420L, 
380L, 45L, 135L, 852L, 1L, 34L, 360L, 140L, 14L, 62L, 501L, 560L, 
0L, 640L, 0L, 0L, 16L, 0L), DocumentNum = c(36L, 4L, 41L, 41L, 
36L, 4L, 41L, 41L, 33L, 33L, 33L, 36L, 4L, 41L, 41L, 33L, 33L, 
33L, 62L, 63L, 62L, 63L, 36L, 4L, 41L)), .Names = c("SaleCount", 
"DocumentNum"), class = "data.frame", row.names = c(NA, -25L))

i need create the column, but this column must be second by order. If i do so: df["MY_NEW_COLUMN"] <- NA . The new colums is third. How it create that it was second by order? I.E. i expect output

      SaleCount newcolumn DocumentNum
1          7        NA          36
2         35        NA           4
3        340        NA          41
4        260        NA          41
5          3        NA          36
6         31        NA           4
7        420        NA          41
8        380        NA          41
9         45        NA          33
10       135        NA          33
11       852        NA          33
12         1        NA          36
13        34        NA           4
14       360        NA          41
15       140        NA          41
16        14        NA          33
17        62        NA          33
18       501        NA          33
19       560        NA          62
20         0        NA          63
21       640        NA          62
22         0        NA          63
23         0        NA          36
24        16        NA           4
25         0        NA          41

Of course sometimes I need to create a fourth column by order and so on.

psysky
  • 3,037
  • 5
  • 28
  • 64

1 Answers1

1

You can use the dplyr library and the select function.

library(dplyr)
df=structure(list(SaleCount = c(7L, 35L, 340L, 260L, 3L, 31L, 420L, 
380L, 45L, 135L, 852L, 1L, 34L, 360L, 140L, 14L, 62L, 501L, 560L, 
0L, 640L, 0L, 0L, 16L, 0L), DocumentNum = c(36L, 4L, 41L, 41L, 
36L, 4L, 41L, 41L, 33L, 33L, 33L, 36L, 4L, 41L, 41L, 33L, 33L, 
33L, 62L, 63L, 62L, 63L, 36L, 4L, 41L)), .Names = c("SaleCount", 
"DocumentNum"), class = "data.frame", row.names = c(NA, -25L))

df["MY_NEW_COLUMN"] <- NA

select(df,SaleCount, MY_NEW_COLUMN, DocumentNum)
Kresten
  • 1,758
  • 12
  • 18