简体   繁体   中英

R: Splitting dataframe columnwise

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.

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)])

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)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM