Problem writing function --- indexing issue

I am trying to run the code below and RStudio and R go crazy. I imagine that there is some way to do this out = dat[, cc[nn1] but I cannot even think of any search terms

dat1 <- data.frame(xx =  LETTERS[1:5], yy = 1:5)

Fn3 <- function(dat, cc, nn1){
out = dat[, cc[nn1]
out
}

Fn3(dat1,  xxx, 1 )

This code is fine

dat1 <- data.frame(xx =  LETTERS[1:5], yy = 1:5)

Fn2 <- function(dat, nn1){
  out = dat[, nn1]
  out
}

Fn2(dat1, 1)

Thanks

There is a missing closing bracket in the subsetting of dat in Fn3. Does this do what you want?

dat1 <- data.frame(xx =  LETTERS[1:5], yy = 1:5)
dat1
#>   xx yy
#> 1  A  1
#> 2  B  2
#> 3  C  3
#> 4  D  4
#> 5  E  5
Fn3 <- function(dat, cc, nn1){
  out = dat[, cc[nn1]]
            out
}

xxx <- c(2,1)
Fn3(dat1,  xxx, 1 )
#> [1] 1 2 3 4 5
Fn3(dat1, xxx, 2)
#> [1] "A" "B" "C" "D" "E"

Created on 2024-08-03 with reprex v2.0.2

Yes that does it. Thanks.
But, I do understand the logic. What exactly does this do?

xxx <- c(2,1)

For cc[nn1] to work inside of Fn3, cc has to be a vector. When you wrote

Fn3(dat1, xxx, 1)

the variable xxx was not defined. I defined it with xxx <- c(2,1)so the code would run.

Ah, I think I see but I'm going have to think about it. I still do not understand why 2, 1. I think I've got a mental block in trying to visualize what it is defining.

Thanks again.

Since the example data frame has two columns, only the indexes 1 and 2 are possible. (-1 and -2 also work if you want to exclude columns rather than include them.) I chose the order c(2,1) to show that passing 1 to the argument nn1 selects the first element of xxx, which is 2, so the second column of the data frame gets chosen.

AHA! I think I'm beginning to see it.
Thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.