tataṣe
tataṣe

Reputation: 59

select columns after named columns

I have a data frame of the following form in R

First a b c Second a b c
3 8 1 7 6 8
5 9 4 2 8 5

I'm trying to write something that selects the three columns following "First" & "Second", and puts them into new data frames titled "First" & "Second" respectively. I'm thinking of using the strategy below (where df is the dataframe I outline above), but am unsure how to make it such that R takes the columns that follow the ones I specify

names <- c("First", "Second")
for (i in c){
     i <- (something to specify the 3 columns following df$i)
}

Upvotes: 0

Views: 48

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389055

You can get position of names vector in column names of the data and subset the next 3 columns from it.

names <- c("First", "Second")
inds <- which(names(df) %in% names)
result <- Map(function(x, y) df[x:y], inds + 1, inds + 3)
result

#[[1]]
#  a b c
#1 3 8 1
#2 5 9 4

#[[2]]
#  a b c
#1 7 6 8
#2 2 8 5

To create separate dataframes you can name the list and use list2env

names(result) <- names
list2env(result, .GlobalEnv)

Upvotes: 1

Maurits Evers
Maurits Evers

Reputation: 50698

An option is to split.default to split the data.frame into a list of data.frames

split.default(df, cumsum(names(df) %in% names))
#$`1`
#  First a b c
#1    NA 3 8 1
#2    NA 5 9 4
#
#$`2`
#  Second a b c
#1     NA 7 6 8
#2     NA 2 8 5

The expression cumsum(...) creates the indices according to which to group and split columns.


Sample data

df <- read.table(text = "First  a   b   c   Second  a   b   c
'' 3    8   1   ''  7   6   8
'' 5    9   4   ''  2   8   5", header = T, check.names = F)

Upvotes: 1

Related Questions