PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

[FIXED] How to assign data table from global environment as elements into list R (Error in x : subscript out of bounds)

 August 19, 2022     environment-variables, list, r     No comments   

Issue

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

Solution

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


Answered By - www
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing