list() 和 as.list() 在以下用法下有什么區別?如果有任何答案可以解釋為什么結果變得不同,我們將不勝感激。
# Dataset
d1 <- data.table(y1 = c(1, 2, 3),
y2 = c(4, 5, 6))
d2 <- data.table(y1 = c(3, 2, 1),
y2 = c(6, 5, 4))
# The method worked as desired
dt_ls <- list(d1,d2)
lapply(dt_ls
, function(i) sum(is.na(i[[2]])))
> lapply(dt_ls, function(i) sum(is.na(i[[2]])))
[[1]]
[1] 0
[[2]]
[1] 0
此方法給出錯誤:
# The method which return error
lapply(as.list(ls(pattern= "^d1$|^d2$", all.names = TRUE))
, function(i) sum(is.na(i[[2]])))
# Error in i[[2]] : subscript out of bounds
uj5u.com熱心網友回復:
我們可以使用get基于物件名稱來訪問物件。
lapply(ls(pattern= "^d1$|^d2$", all.names = TRUE)
, function(i) sum(is.na(get(i)[[2]])))
# [[1]]
# [1] 0
#
# [[2]]
# [1] 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/490276.html
