I want to know how to use ifelse() statements to get different kinds of objects in R.
Specifically, I want to do this with the mtcars
data, which is a list type object. I used the code below to create a character object version of the name of the data, called mtcars__string_object
.
mtcars__string_object <- c("mtcars")
For the object itself, here is the code I want to use to get this data via an ifelse()
statement, which does not work:
test_1 <-
ifelse(
((typeof(mtcars) == "list") == TRUE),
(mtcars),
NA
)
It does not work because it doesn't give me the dataset in its original form. Here are the results:
> test_1
[[1]]
[1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
[31] 15.0 21.4
When I just use the name of the object, here is the code I want to use to get this data via an ifelse()
statement, which does not work:
test_2 <-
ifelse(
((typeof(mtcars) == "character") == TRUE),
(get(mtcars__string_object[1])),
NA
)
It does not work because it doesn't give me the dataset in its original form. Here are the results:
> test_2
[1] NA
I'm not sure how to fix the code to get the desired result. Please advise. Thanks.
Here is the code that I used for the example:
# StackOverflow materials
## sets up data
### name of object
mtcars
### text object with name of dataset
mtcars__string_object <- c("mtcars")
## checks typeof() of objects
typeof(mtcars)
typeof(mtcars__string_object)
## ifelse() statements to call data
### for object itself
# ---- NOTE: creates object
test_1 <-
ifelse(
((typeof(mtcars) == "list") == TRUE),
(mtcars),
NA
)
# ---- NOTE: displays object
test_1
# ---- NOTE: does not work
### for text object with name of dataset
# ---- NOTE: creates object
test_2 <-
ifelse(
((typeof(mtcars) == "character") == TRUE),
(get(mtcars__string_object[1])),
NA
)
# ---- NOTE: displays object
test_2
# ---- NOTE: does not work
Aucun commentaire:
Enregistrer un commentaire