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
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) .
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.
Assuming your list is called myList
, something like this should work:
lapply(myList, function(x) { x["ID"] <- NULL; x })
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"))])
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With