所以我有一长串的对象,每个对象都有一个我想要删除的插槽.具体而言,它们以重复的方式存储数据.但之所以无所谓.
我的主要问题是什么是"正确"的做法.所以这里是设置:
q <- list()
q$useless <- rnorm(100)
q$useful <- rnorm(100)
SampleList <- list(q,q,q)
Run Code Online (Sandbox Code Playgroud)
所以我有一个相同对象的列表(或至少相同的外观对象).我想删除无用的插槽.为什么,因为它对我没用.
我可以做一个循环:
for (i in 1:length(SampleList)){
SampleList[[i]]$useless <- NULL
}
Run Code Online (Sandbox Code Playgroud)
但为什么lapply()版本不起作用.所以猜测问题是我没有得到什么关于lapply.
lapply(SampleList, function(x){print(x$useless) })
SampleList<- lapply(SampleList, function(x){x$useless <- NULL }) #NO WORK
Run Code Online (Sandbox Code Playgroud)
lapply中的函数没有返回任何内容,所以它默认返回你的赋值结果.您需要返回修改后的对象才能使用您的版本
SampleList <- lapply(SampleList, function(x){x$useless <- NULL; x})
Run Code Online (Sandbox Code Playgroud)