我有一个(数据帧)列表的命名列表。
l_of_lists <- list(
fruits = list(
red = data.frame("apple", "cherry", "strawberry"),
yellow = data.frame("banana", "lemon"),
orange = data.frame("orange", "grapefruit", "blood orange")),
colors = list(
green = data.frame("light green", "green", "dark green"),
red = data.frame("red", "dark red"),
blue = data.frame("light blue", "blue", "dark blue")),
places = list(
inside = data.frame("living room", "bathrooom", "kitchen"),
outside = data.frame("garden", "yard"),
neighborhood = data.frame("playground", "shop", "school"))
)
Run Code Online (Sandbox Code Playgroud)
我遍历l_of_lists的sublists确定每个数据帧的列数,我想删除每一个sublist不符合条件(在这个例子是,它有三列)。
使用以下代码:
for (ls in l_of_lists){
for (sublist in ls){
if (!ncol(sublist) == 3)
{
print(ncol(sublist))
#sublist <- NULL # this does achieve the desired result
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何删除根据条件确定的子列表?(我敢肯定有一种更有效的方法可以完成此操作,我很高兴收到有关此操作的提示。)
调用没有3列的元素会容易得多:
lapply(l_of_lists,function(i)i[sapply(i,length)==3])
Run Code Online (Sandbox Code Playgroud)
有了sapply,您就可以遍历l_of_list的每个元素以获得列数的向量。您可以使用此子集来划分具有3列的那些子集。
如果要删除,请尝试此操作
l_of_lists = lapply(l_of_lists,function(i)i[sapply(i,length)==3])
Run Code Online (Sandbox Code Playgroud)
如果要使用循环,那么最好使用索引而不是对象:
for (i in 1:length(l_of_lists)){
sublist = l_of_lists[[i]]
for (j in 1:length(sublist)){
obj = sublist[[j]]
if (!ncol(obj) == 3)
{
print(ncol(obj))
l_of_lists[[i]][[j]] <- NULL # this does achieve the desired result
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |