R: Create multiple new columns based upon other columns

后端 未结 2 354
心在旅途
心在旅途 2021-01-22 10:59

Let\'s say I have a data-frame that looks like this

dd <- read.table(header = TRUE, text = \"ID week1_t week1_a  week2_t week2_a
  1      12      22       17          


        
2条回答
  •  再見小時候
    2021-01-22 11:25

    We split the 'week' columns (dd[-1]) by the names of the dataset after removing the suffix with sub into a list, get the difference between the two columns and assign the list elements to create new columns in 'dd'.

    lst <-  lapply(split.default(dd[-1], 
               sub("_.*", "", names(dd)[-1])), function(x) x[2]-x[1])
    dd[paste0("week_", seq_along(lst), "d")] <- lapply(lst, unlist, use.names=FALSE)
    dd
    #    ID week1_t week1_a week2_t week2_a week1_d week2_d
    #1  1      12      22      17       4      10     -13
    #2  1      15      32      18       5      17     -13
    #3  1      24      12      29       6     -12     -23
    #4  2      45      11      19       8     -34     -11
    #5  2      23      33      20      10      10     -10
    

    If the columns are alternating i.e. 'week1_t' followed by 'week1_a', then 'week2_t', followed by 'week2_a', etc.

    Un1 <- unique(sub("_.*", "", names(dd)[-1]))
    i1 <-  c(TRUE, FALSE)
    dd[paste0(Un1, "_d")] <-  dd[-1][!i1]- dd[-1][i1]
    dd
    #  ID week1_t week1_a week2_t week2_a week1_d week2_d
    #1  1      12      22      17       4      10     -13
    #2  1      15      32      18       5      17     -13
    #3  1      24      12      29       6     -12     -23
    #4  2      45      11      19       8     -34     -11
    #5  2      23      33      20      10      10     -10
    

提交回复
热议问题