Reputation: 589
I have a dataframe with the this structure
x = data.frame(let = letters, LET = LETTERS, num1 = 1:26, num2 = 21:46, num3 = 71:96, num4 = 68:93 )
I want to split it into list of 3 columns dataframes.The first two columns let and LET remains common, the third column varies. The first dataframe would be (let, LET, num1) and the second one would be (let, LET, num2) and so on so forth.
My current strategy is to convert the dataframe into long format and split it based on the num using plyr and dplyr packages. Is there an easier way to accomplish this task.
Upvotes: 1
Views: 210
Reputation: 887951
Here is a Map
based approach
Map(function(x,y,z) setNames(cbind(x,y), c(names(x), z)),
list(x[1:2]), x[-(1:2)], names(x)[-(1:2)])
Upvotes: 2
Reputation: 16099
You can use lapply
like so for your example
lapply(1:4, function(D) x[ ,c("let", "LET", paste0("num", D))])
If you don't know the column names of the num*
columns you could use
nonLetNames <- names(x)[!(names(x) %in% c("let", "LET"))]
lapply(nonLetNames, function(nom) x[ ,c("let", "LET", nom)])
Upvotes: 2