I\'ve the below dataframe with 10 columns.
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19
We can use seq
to create the index of alternating columns, loop along and then subset the dataset
lst1 <- lapply(seq(1, ncol(df1), by=2), function(i)
df1[i: pmin((i+1), ncol(df1))])
Or use split
lst2 <- lapply(split(seq_along(df1),as.numeric(gl(ncol(df1),
2, ncol(df1)))), function(i) df1[i])
If we need 5 individual datasets in the global environment, use list2env
(not recommended though)
list2env(setNames(lst1, paste0("newdf", seq_along(lst1))),
envir=.GlobalEnv)
df1 <- structure(list(V1 = c(1L, 11L, 21L, 31L, 41L, 51L, 61L, 71L,
81L, 91L), V2 = c(2L, 12L, 22L, 32L, 42L, 52L, 62L, 72L, 82L,
92L), V3 = c(3L, 13L, 23L, 33L, 43L, 53L, 63L, 73L, 83L, 93L),
V4 = c(4L, 14L, 24L, 34L, 44L, 54L, 64L, 74L, 84L, 94L),
V5 = c(5L, 15L, 25L, 35L, 45L, 55L, 65L, 75L, 85L, 95L),
V6 = c(6L, 16L, 26L, 36L, 46L, 56L, 66L, 76L, 86L, 96L),
V7 = c(7L, 17L, 27L, 37L, 47L, 57L, 67L, 77L, 87L, 97L),
V8 = c(8L, 18L, 28L, 38L, 48L, 58L, 68L, 78L, 88L, 98L),
V9 = c(9L, 19L, 29L, 39L, 49L, 59L, 69L, 79L, 89L, 99L),
V10 = c(10L, 20L, 30L, 40L, 50L, 60L, 70L, 80L, 90L, 100L
)), .Names = c("V1", "V2", "V3", "V4", "V5", "V6", "V7",
"V8", "V9", "V10"), class = "data.frame", row.names = c(NA, -10L
))