简体   繁体   中英

How to write a function for a variable name?

I have an object that is st

str(st)
List of 34
$ cell_ele    : num [1:2000, 1:1000] 999 999 ...

Now I want to write a function

myfun <- function(var){
rt= st$var 
rt=raster(rt)
out <- writeRaster(rt, filename = "C:\\var_data")
                      }

var will be used twice , to be read and then to be part of the output file name

 myfun (cell_ele)
 Error in raster(matrix(data = rt)) : 
 error in evaluating the argument 'x' in selecting a method for function 
'data' must be of a vector type, was 'NULL'

I tried it without the function and it worked fine. The problem is in the function

Take a look at this command written inside the function's body:

rt= st$var

This will look for a column named var of the variable st . It will not substitute var with the contents of the variable given as an argument.

Instead, you should have written:

rt = st[var]

So please alter your function like so:

myfun <- function(var){
  rt= st[var]
  rt=raster(rt)
  out <- writeRaster(rt, filename = paste("C:\\", var, "_data", sep=""))
}

which will do the substitution and look for a column whose name is defined by the argument you are passing to the function. We are also using the function paste , since we want to have a variable name:

paste converts its arguments (via as.character) to character strings, and concatenates them (separating them by the string given by sep). If the arguments are vectors, they are concatenated term-by-term to give a character vector result.

Also, you should pass a string argument:

myfun ("cell_ele")

The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors. Note though that for a list or other recursive object, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.

The form using $ applies to recursive objects such as lists and pairlists. It allows only a literal character string or a symbol as the index. That is, the index is not computable: for cases where you need to evaluate an expression to find the index, use x[[expr]]. When $ is applied to a non-recursive object the result used to be always NULL: as from R 2.6.0 this is an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM