我想分别分析 75 个数据文件,但都采用相同的方式。我为分析的每一步都编写了函数。数据集基本上是这样的:
df = data.frame(
Time = c(1, 2, 3, 4),
Concentration = c(2983, 9848, 2894, 8384))
我向用户询问文件名,我想在函数中输入选择的文件名。
enterFileName <- function(){
filename <- readline(prompt="Enter file name: ")
return(filename)}
我有两个问题:
是否可以编写代码,以便在我运行函数时自动使用用户输入的文件名(使用我之前创建的变量“filename”)?这样我就不用每次都重复输入文件名了。我试过这个,但它不起作用:
averageFun <- function(){ summary(filename$Concentration)} enterFileName() averageFun() Error in summary(filename$Concentration) : object 'filename' not found
我可以使用用户输入的文件名作为 ggplot 图表中的主标题吗?像这样的……
plotFirst <- function(df){ ggplot(data = df, aes(x = Time, y = Number)) + geom_line() + ggtitle("UFP concentrations raw data" + filename) }
这只会返回一个没有主标题的图表。
有人可以帮我解决这个问题吗?提前致谢!
最佳答案
enterFileName()
没有副作用,您不会在工作区中创建任何名为 filename
的变量。
你好像在引用一个变量,称它为文件名,这很困惑,但你应该从这里找到你的方法:
方案一,使用变量
df = data.frame(
Time = c(1, 2, 3, 4),
Concentration = c(2983, 9848, 2894, 8384))
enterFileName <- function(){
filename <- readline(prompt="Enter file name: ")
return(filename)}
averageFun <- function(filename){
summary(get(filename)$Concentration)}
filename <- enterFileName() # we enter 'df' (without quotes)
averageFun(filename)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 2894 2961 5684 6027 8750 9848
plotFirst <- function(df, filename){
library(ggplot2)
ggplot(data = df, aes(x = Time, y = Concentration)) + geom_line() +
ggtitle(paste("UFP concentrations raw data" ,filename))
}
plotFirst(df,filename)
方案二,使用选项
enterFileName <- function(){
options(myproject.filename = readline(prompt="Enter file name: "))
}
averageFun <- function(){
summary(get(getOption("myproject.filename"))$Concentration)}
filename <- enterFileName() # we enter 'df' (without quotes)
averageFun()
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 2894 2961 5684 6027 8750 9848
plotFirst <- function(df){
library(ggplot2)
ggplot(data = df, aes(x = Time, y = Concentration)) + geom_line() +
ggtitle(paste("UFP concentrations raw data" ,getOption("myproject.filename")))
}
plotFirst(df,filename)
关于r - 用户在函数中输入文件名 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51630699/