2014-11-01 51 views
1

我对R编程相当陌生,所以我的问题可能显得太天真了。 我想在一个文件中定义R的所有函数,命名为functions.R,并在需要时调用它。我想用source()。功能不能对R中的数据集进行操作

这是我的代码:

main.R:

library(gstat) 
library(lattice) 
library(rgdal) 

source("functions.R") 
source("script_import.R") 

script_import.R:

source("functions.R") 

#Here I import the dataset named "dati" 
dati<-read.csv2("/home/eugen/Documenti/file_da_importare.csv", header = TRUE, skip=4, dec = ",") 

colnames(dati)<-c("provider", "ente", "nome_stazione", "long", "lat", "quota", "periodo_dati", "anni_dati", "tm_01", "tm_02", "tm_03", "tm_04", "tm_05", "tm_06", "tm_07", "tm_08", "tm_09", "tm_10", "tm_11", "tm_12", "remove", "tn_01", "tn_02", "tn_03", "tn_04", "tn_05", "tn_06", "tn_07", "tn_08", "tn_09", "tn_10", "tn_11", "tn_12", "remove1", "tx_01", "tx_02", "tx_03", "tx_04", "tx_05", "tx_06", "tx_07", "tx_08", "tx_09", "tx_10", "tx_11", "tx_12", "stato", "note", "nazione") 

#That's the function call with which I have problems 
clean_main_ds() 

#If I use this commands instead of the function all works well 
#dati$remove<-NULL 
#dati$remove1<-NULL 

functions.R:

clean_main_ds<-function(){ 
    #I want to delete two columns 
    dati$remove<-NULL 
    dati$remove1<-NULL 
    cat("I'm exiting the function") 
    return(dati) 
} 

当编译我不”如果收到任何错误,则会显示该功能s在rstudio中声明,被script_import.R调用,cat()运行良好(所以我认为调用没有问题),但函数不会删除这两列。如果我在script_import.R中使用相同的命令(“dati $ remove < -NULL”),而不是该函数,则所有的都可以正常工作。 错误在哪里?我该如何让我的函数对另一个文件中定义的数据集进行操作?

非常感谢您的帮助, 尤金

诗:对不起,在语言的错误,我不是英语。我希望文本已经足够清晰了......

+0

使用诸如'dati $ remove < - NULL'之类的调用仅在'remove'是实际名称时才有效。如果你想正确读取'?'[''并避免'$'函数的语法糖。 (这也是关于SO的高度重复的问题。)此外,你似乎没有分配函数的值,所以它只是被垃圾收集。 – 2014-11-01 15:53:24

+0

谢谢,它的工作!我认为函数self修改了全局数据集,我不认为我需要重新分配这个值。是的,删除它是要删除列的名称。真的感谢! – Eugen 2014-11-01 16:09:33

回答

1

当您在函数内使用赋值运算符<-时,它只会在函数自己的环境中执行赋值。即,函数创建对象dati的副本,然后将NULL分配给功能环境内的元素removeremove1dati

现在,当您使用return时,该功能将返回原始对象dati的此修改副本。它会在不是修改全球环境中的对象dati。如果你使用str(clean_main_ds()),你会注意到这个对象实际上是你的数据框,并删除了这些列。

有几件事你可以做,以解决这个问题。

clean_main_ds<-function(){ 
     #I want to delete two columns 
     dati$remove<<-NULL 
     dati$remove1<<-NULL 
     cat("I'm exiting the function") 
     return(dati) 
    } 

(事实上,这样做,你甚至不需要最后:首先,你可以使用赋值运算符<<-,这将在全球环境,而不是函数自身的环境做分配指定功能行return(dati)在功能。当你到达那里你的功能已经完成对你的对象在全球环境中的修改。)

另一种选择是只分配原始函数返回的值到原始数据帧由 dati <- clean_main_ds()

最后,您可以通过使用索引直接从数据框中删除列,而无需为其编写函数。

dati <- dati[ , -which(colnames(dati) %in% c("remove", "remove1"))] 

(您可以通过只指定列的列数删除,而不是which()段直接做到这一点。这部分只是看起来了他的名字是removeremove1列的索引。)

+0

谢谢,你的回答非常清楚 – Eugen 2014-11-02 08:30:06