简体   繁体   中英

R Functions require package declaration when they are included from another file?

I am writing some data manipulation scripts in R, and I finally decided to create an external .r file and call my functions from there. But it started giving me some problems when I try calling some functions. Simple example:

This one works with no problem:

change_column_names <- function(file,new_columns,seperation){
    new_data <- read.table(file, header=TRUE, sep=seperation)
    colnames(new_data) <- new_columns
    write.table(new_data, file=file, sep=seperation, quote=FALSE, row.names = FALSE)
}
change_column_names("myfile.txt",c("Column1", "Column2", "Cost"),"|")

When I crate a file "data_manipulation.r", and put the above change_column_names function in there, and do this

sys.source("data_manipulation.r")
change_column_names("myfile.txt",c("Column1", "Column2", "Cost"),"|")

it does not work. It gives me could not find function "read.table" error. I fixed it by changing the function calls to util:::read.table and util:::write.table .

But this kinda getting frustrating. Now I have the same issue with the aggregate function, and I do not even know what package it belongs to.

My questions: Which package aggregate belongs to? How can I easily know what packages functions come from? Any cleaner way to handle this issue?

The sys.source() by default evaluates inside the base environment (which is empty) rather than the global environment (where you usually evaluate code). You probably should just be using source() instead.

You can also see where functions come from by looking at their environment.

environment(aggregate)
# <environment: namespace:stats>

For the first part of your question: If you want to find what package a function belongs to, and that function is working properly you can do one of two (probably more) things:

1.) Access the help files

?aggregate and you will see the package it belongs to in the top of the help file.

Another way, is to simply type aggregate without any arguments into the R console:

> aggregate
function (x, ...) 
UseMethod("aggregate")
<bytecode: 0x7fa7a2328b40>
<environment: namespace:stats>

The namespace is the package it belongs to.

2.) Both of those functions that you are having trouble with are base R functions and should always be loaded. I was not able to recreate the issue. Try using source instead of sys.source and let me know if it alleviates your 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