Home > Back-end >  Crete a variable "mydata" - A data structure that outputs the following
Crete a variable "mydata" - A data structure that outputs the following

Time:01-21

I am struggling to find a way to implement a matrix to my list. $mix$b becomes a character vector. Please help.

This is the task

# Create a variable "mydata" - a data structure with the output presented 
# below as comments

# > print(mydata)
# [[1]]
# [1] "Some long text"
# 
# [[2]]
# [1] 1 2 3 4 5
# 
# $mix
# $mix$a
# [1] "text"
# 
# $mix$b
#   a  b  c
# 1 a -2  3
# 2 b  0  4
# 3 c  2 -5
# 4 d  4 77 

This is my best attempt

mydata <- list("Some long text", 1:5, 
               mix = list(a = 'text', b = c(a = "a", b = -2, c = 3)))
mydata

output

[[1]]
[1] "Some long text"

[[2]]
[1] 1 2 3 4 5

$mix
$mix$a
[1] "text"

$mix$b
   a    b    c 
 "a" "-2"  "3" 

CodePudding user response:

mydata <- list("Some long text", 1:5, 
               mix = list(a = 'text', 
                          b = data.frame(a = c("a", "b", "c", "d"),
                                         b = c(-2,0,2,4),
                                         c = c(3,4,-5,77))))
mydata

[[1]]
[1] "Some long text"

[[2]]
[1] 1 2 3 4 5

$mix
$mix$a
[1] "text"

$mix$b
  a  b  c
1 a -2  3
2 b  2  4
3 c  0 -5
4 d  4 77

Here are some example how to extract the 77:

mydata$mix$b[4,3]
mydata[[3]][[2]][4,3]
mydata[["mix"]][["b"]][4,3]
mydata[[3]][["b"]][4,3]
mydata[["mix"]][[2]][4,3]

77
  •  Tags:  
  • Related