0

I have an R function that generates and returns a list of (a) train and (b) test data partitions based on raw data.

I have applied this function to the R iris dataset. Then I feed the train data partition into a lda model. The truncated output and error message (from the lda part) are shown below.

Here is a code snippet:

myfunc <- function(rawdata,) {
    ....
    return(list(train,test))}

dfs = create_data_partition(mydf)
dfs[1]
dfs[2]

control <- trainControl(method="cv", number=10)
metric <- "Accuracy"

set.seed(7)
fit_lda <- train(Species~., data=dfs[1], method="lda", metric=metric, trControl=control)

Here is the output:

[[1]]
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1            5.1         3.5          1.4         0.2     setosa
2            4.9         3.0          1.4         0.2     setosa
.
.
150          5.9         3.0          5.1         1.8  virginica

[[1]]
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
18           5.1         3.5          1.4         0.3     setosa
19           5.7         3.8          1.7         0.3     setosa
.
.
125          6.7         3.3          5.7         2.1  virginica
134          6.3         2.8          5.1         1.5  virginica
138          6.4         3.1          5.5         1.8  virginica

Error in eval(expr, envir, enclos) : object 'Species' not found
Calls: train ... eval -> <Anonymous> -> model.frame.default -> eval -> eval
Execution halted

I think the problem is that dfs[1] is not a dataframe - instead it has [[1]] in front of it. This is an artifact of how I have returned multiple values in the function myfunc - I think this return(list(train,test)) is somehow incorrectly formatted but I am not sure why this is happening.

Question After calling an R function that returns multiple values (in a list), is there a way to access the returned values separately?

edesz
  • 11,756
  • 22
  • 75
  • 123

1 Answers1

1

Single list elements are extracted using the double square bracket notation: [[. If you wish to extract the first list element and not produce a new list, you need

dfs[[1]]

This is spelled out a little more clearly in the Language Definition.

josliber
  • 43,891
  • 12
  • 98
  • 133
Jonathan Carroll
  • 3,897
  • 14
  • 34
  • I *think* I was also thinking along those lines. However, what I had incorrectly tried was: `dfs[1][1]`. I assumed the second `[1]` would have done the trick to avoid creating a new list. – edesz Jun 28 '17 at 15:24