Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a column in a data frame within a list

Tags:

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

$A ID Test A   1 A   1  $B  ID Test  B   1  B   3  B   5 

Into this

$A Test  1  1  $B Test  1  3  5 
like image 788
ego_ Avatar asked Sep 30 '12 19:09

ego_


People also ask

How do you delete a column in a list in R?

For example, if you want to remove the columns “X” and “Y” you'd do like this: select(Your_Dataframe, -c(X, Y)) . Note, in that example, you removed multiple columns (i.e. 2) but to remove a column by name in R, you can also use dplyr, and you'd just type: select(Your_Dataframe, -X) .

How do you remove columns from a data set?

The most easiest way to drop columns is by using subset() function. In the code below, we are telling R to drop variables x and z. The '-' sign indicates dropping variables. Make sure the variable names would NOT be specified in quotes when using subset() function.


2 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"))]) 
like image 150
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 24 '22 22:10

A5C1D2H2I1M1N2O1R2T1


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))) 
like image 22
Giorgi Chighladze Avatar answered Oct 24 '22 23:10

Giorgi Chighladze