Reputation: 85
I have a function:
extract_tmp <- function(x,y)
{
nr <- nrow(x$y)
ind <- seq(6, nr, by = 12)
out <- lapply(Map(seq, ind[ seq_along(ind) %% 2 == 1 ], ind[ seq_along(ind) %% 2 == 0 ]),
function(i) x$y[i])
}
When I call:
extract_tmp(JAN , tmp.2007.jan)
it returns:
Error in seq.default(6, nr, by = 12) : 'to' must be of length 1
and when i switch nrow()
to length()
it returns:
Error in seq.default(6, nr, by = 12) : wrong sign in 'by' argument
I have been reading this site and troubleshooting for a few hours, and unable to resolve these. Additional info:
length(JAN$tmp.2007.jan)
# 744
nrow(JAN$tmp.2007.jan)
# NULL
mode(JAN)
# "list"
mode(JAN$tmp.2007.jan)
# "numeric"
Thanks for any help.
Upvotes: 0
Views: 624
Reputation: 160587
extract_tmp <- function(x, y) {
nr <- nrow(x)
ind <- seq(6, nr, by = 12)
out <- lapply(Map(seq, ind[ seq_along(ind) %% 2 == 1 ], ind[ seq_along(ind) %% 2 == 0 ]),
function(i) x[[y]][i])
out
}
extract_tmp(mtcars, "cyl")
# [[1]]
# [1] 6 8 4 4 6 6 8 8 8 8 8 8 4
# [[2]]
# [1] 6 8 4 4 4 8 8 8 8 4 4 4 4
Things fixed:
In a general sense, you cannot pass a column name like that un-quoted. I suggest instead that you pass a string for the second argument and use x[[y]]
instead of x$y
. (It is possible using substitute
and other NSE (non-standard evaluation) methods, but when beginning in R, I suggest you stay with standard evaluation.
nrow
operates on frames, not vectors, so nrow(x)
or length(x[[y]])
.
Not a problem, per se, but it might appear to be one. You were not explicitly returning out
from your function. In R, in a code block the last expression is typically returned. When that last expression is an assignment (<-
), then its value is invisibly returned as well (which is why a <- b <- 2
works: the expression b <- 2
invisibly returns the value assigned, which then cascades to a <- 2
.
In this case, without adding the explicit out
as I did above, it will still return the results you need, but it will appear to do nothing: extract_tmp(mtcars, "cyl")
will appear to return nothing, but if you assign the results to a variable and look at that, or if you call (extract_tmp(mtcars, "cyl"))
instead (surrounding parens), then you'll see the output.
In general, I strongly suggest you be explicit about your return variables. One reason is declarative code. Another reason is that sometimes the last expression does not work on all the values needed. For instance, consider this block:
x <- 1:10
x[3] <- 99
in this case, the last assignment has the value 99, not the contents of x
, so if you were intending the return value to be the whole vector, then you'd be missing out.
Upvotes: 1