What is the difference between list() and as.list() under the usage as below ? appreciated if any answer can explain why the result turned different .
# 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
This method gives error :
# 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
CodePudding user response:
We can use get
to access the object based on the object name.
lapply(ls(pattern= "^d1$|^d2$", all.names = TRUE)
, function(i) sum(is.na(get(i)[[2]])))
# [[1]]
# [1] 0
#
# [[2]]
# [1] 0