Select some column in a loop and save separately

后端 未结 2 518
遇见更好的自我
遇见更好的自我 2021-01-29 17:11

My data frame is

c1  c2  c3  c100
0.2 0.4 0.9 0
0.2 0.3 0   1
0.1 0.6 1   0.3

I want ot select c1 c2 and c3, the c1 c2 and c4, similarly c1 c2

相关标签:
2条回答
  • 2021-01-29 17:24

    assuming that x is your data.frame you can use this:

    for (i in 3:100){
      tmp <- x[, c(1,2,i)]
      write.table(tmp, paste0("some/file/path/and/name_", i, ".csv"))
    }
    

    By using the iterator i for the file name, you can create individual file names.

    0 讨论(0)
  • 2021-01-29 17:36

    We can use combn

    lst <- combn(df1, 3, FUN = list)
    names(lst) <-  sapply(lst, function(x) paste(names(x), collapse="_"))
    lapply(names(lst), function(x) write.table(lst[[x]], paste0(x, ".csv")))
    

    If it is append 1st and 2nd columns with all the other columns

    lst <- lapply(names(df1)[3:100], function(i) df1[c(1:2, i)])
    names(lst) <-  sapply(lst, function(x) paste(names(x), collapse="_"))
    lapply(names(lst), function(x) write.table(lst[[x]], paste0(x, ".csv")))
    
    0 讨论(0)
提交回复
热议问题