Adrian Smith
Adrian Smith

Reputation: 139

Splitting columns in a data frame to a list in R

I'm looking to convert a predefined number of columns (including all rows) in a data frame to an item in a list (i.e. the first item in a list would be a data frame including columns 1-3 of the original df, the second item would include columns 4-6, the third would include columns 7-9 etc.).

Is there a function to achieve that?

Thanks

Upvotes: 2

Views: 59

Answers (3)

moodymudskipper
moodymudskipper

Reputation: 47300

Using lapply with [ you can get what you want :

df <- head(mtcars)[1:9]               # create a 9 column df
subdiv <- split(1:9,rep(1:3,each=3))  # splitting by 3, but you can put any subdivision in a list

lapply(subdiv,function(x,y) y[x],df)
# $`1`
# mpg cyl disp
# Mazda RX4         21.0   6  160
# Mazda RX4 Wag     21.0   6  160
# Datsun 710        22.8   4  108
# Hornet 4 Drive    21.4   6  258
# Hornet Sportabout 18.7   8  360
# Valiant           18.1   6  225
# 
# $`2`
# hp drat    wt
# Mazda RX4         110 3.90 2.620
# Mazda RX4 Wag     110 3.90 2.875
# Datsun 710         93 3.85 2.320
# Hornet 4 Drive    110 3.08 3.215
# Hornet Sportabout 175 3.15 3.440
# Valiant           105 2.76 3.460
# 
# $`3`
# qsec vs am
# Mazda RX4         16.46  0  1
# Mazda RX4 Wag     17.02  0  1
# Datsun 710        18.61  1  1
# Hornet 4 Drive    19.44  1  0
# Hornet Sportabout 17.02  0  0
# Valiant           20.22  1  0

Upvotes: 2

Frostic
Frostic

Reputation: 680

You can loop over 3,6,.. up to the length of your vector and select 1:3, 4:6,... columns with a lapply. Alike a loop but faster, more compact and gives you the desired ouput.

lapply(3*(1:(ncol(df)%/%3)),function(x) df[,(x-2):x])

Upvotes: 2

Dick McManus
Dick McManus

Reputation: 789

I am not sure if this exactly answers your question but if you simply are trying to select columns in a data frame based on their number 1:n. The following will work.

List1 = dataframe[,1:3]
List2 = dataframe[,4:6]
List3 = dataframe[,7:9]

This will create three new dataframes from each of your desired columns.

Upvotes: 0

Related Questions