I have read and used the answers to the following question ( Remove specific data frame from a list of data frames in R ), where one specific data frame was to be removed from a list. I now need to build on this but am struggling to find the right solution. I have a list of 48 data frames and would like to remove several items from the list, is there a similar code I can use?
Using the same example as the similar question, if to remove $d2 is my.list = my.list[-2]
, how would I remove $d2, $d3 and $d6 - ideally at the same time, or one at a time?
Writing the same code consecutively doesn't appear to work, eg.
my.list = my.list[-2]
my.list = my.list[-3] #or should this be [-2] as [3] has become [2] when i removed the original [2]
my.list = my.list[-6] #same again
my.list
$d1
y1 y2
1 1 4
2 2 5
3 3 6
$d2
y1 y2
1 3 6
2 2 5
3 1 4
$d3
y1 y2
1 1 4
2 2 5
3 3 6
$d4
y1 y2
1 3 6
2 2 5
3 1 4
$d5
y1 y2
1 1 4
2 2 5
3 3 6
$d6
y1 y2
1 3 6
2 2 5
3 1 4
There are a variety of valid answers in the comments using numeric indices. Here's yet another:
my.list2 <- my.list[ ! #negation operator
names(my.list) %in% c('d2','d3','d6') ] #logical index
#check
> my.list2
$d1
y1 y2
1 1 4
2 2 5
3 3 6
$d4
y1 y2
1 3 6
2 2 5
3 1 4
$d5
y1 y2
1 1 4
2 2 5
3 3 6
The reason your attempt failed is that the sequence of values in my.list
changed as soon as you removed the first item. Notice that I assigned to a different named item. That's a much safer strategy.
The reason I added a demonstration of a logical indexing scheme is its superior generality. You can instead define a criterion that you might use on each item in turn using sapply
. The logical vector that results can be used as a selection vector.
Example for testing:
dput(my.list)
list(d1 = structure(list(y1 = 1:3, y2 = 4:6), class = "data.frame", row.names = c("1",
"2", "3")), d2 = structure(list(y1 = 3:1, y2 = 6:4), class = "data.frame", row.names = c("1",
"2", "3")), d3 = structure(list(y1 = 1:3, y2 = 4:6), class = "data.frame", row.names = c("1",
"2", "3")), d4 = structure(list(y1 = 3:1, y2 = 6:4), class = "data.frame", row.names = c("1",
"2", "3")), d5 = structure(list(y1 = 1:3, y2 = 4:6), class = "data.frame", row.names = c("1",
"2", "3")), d6 = structure(list(y1 = 3:1, y2 = 6:4), class = "data.frame", row.names = c("1",
"2", "3")))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.