Delete a column in a data frame in a list

I made a list from my data framework based on factor levels in column A. In the list, I would like to delete this column. My head speaks latently, but not something else: P

$A
ID Test
A   1
A   1

$B
 ID Test
 B   1
 B   3
 B   5

In that

$A
Test
 1
 1

$B
Test
 1
 3
 5
+8
source share
4 answers

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"))])
+30
source

If you are a user tidyversethere is an alternative solution that uses the function mapfrom the package purrr.

# 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)))
+3
source

, ID, map_if , .

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

"[" .

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

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

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
source

All Articles