Delete a column in a data frame within a list

后端 未结 4 1377
小鲜肉
小鲜肉 2020-12-03 03:44

I made a list out of my dataframe, based on the factor levels in column A. In the list I would like to remove that column. My head is saying lapply, but not anything else :P

相关标签:
4条回答
  • 2020-12-03 03:53

    We can efficiently use the bracket function "[" here.

    Example

    L <- replicate(3, iris[1:3, 1:4], simplify=FALSE)  # example list
    

    Delete columns by numbers

    lapply(L, "[", -c(2, 3))
    

    Delete columns by names

    lapply(L, "[", -grep(c("Sepal.Width|Petal.Length"), names(L[[1]])))
    

    Result

    # [[1]]
    #   Sepal.Length Petal.Width
    # 1          5.1         0.2
    # 2          4.9         0.2
    # 3          4.7         0.2
    # 
    # [[2]]
    #   Sepal.Length Petal.Width
    # 1          5.1         0.2
    # 2          4.9         0.2
    # 3          4.7         0.2
    
    0 讨论(0)
  • 2020-12-03 03:53

    If you had a data frame that didn't contain the ID column, you could use map_if to remove it only where it exists.

    myList <- list(A = data.frame(ID = c("A", "A"), 
                              Test = c(1, 1), 
                              Value = 1:2), 
               B = data.frame(ID = c("B", "B", "B"), 
                              Test = c(1, 3, 5), 
                              Value = 1:3),
               C = data.frame(Test = c(1, 3, 5), 
                              Value = 1:3))
    map_if(myList, ~ "ID" %in% names(.x), ~ .x %>% select(-ID), .depth = 2)
    
    0 讨论(0)
  • 2020-12-03 04:08

    Assuming your list is called myList, something like this should work:

    lapply(myList, function(x) { x["ID"] <- NULL; x })
    

    Update

    For a more general solution, you can also use something like this:

    # Sample data
    myList <- list(A = data.frame(ID = c("A", "A"), 
                                  Test = c(1, 1), 
                                  Value = 1:2), 
                   B = data.frame(ID = c("B", "B", "B"), 
                                  Test = c(1, 3, 5), 
                                  Value = 1:3))
    # Keep just the "ID" and "Value" columns
    lapply(myList, function(x) x[(names(x) %in% c("ID", "Value"))])
    # Drop the "ID" and "Value" columns
    lapply(myList, function(x) x[!(names(x) %in% c("ID", "Value"))])
    
    0 讨论(0)
  • 2020-12-03 04:12

    If you are tidyverse user there is an alternative solution, which utilizes map function from purrr package.

    # Create same sample data as above
    myList <- list(A = data.frame(ID = c("A", "A"), 
                                  Test = c(1, 1), 
                                  Value = 1:2), 
                   B = data.frame(ID = c("B", "B", "B"), 
                                  Test = c(1, 3, 5), 
                                  Value = 1:3))
    # Remove column by name in each element of the list
    map(myList, ~ (.x %>% select(-ID)))
    
    0 讨论(0)
提交回复
热议问题