【问题标题】:Want to write a function that takes a csv file as an argument想写一个以 csv 文件为参数的函数
【发布时间】:2025-11-25 19:55:01
【问题描述】:

我正在尝试编写一个将 csv 文件作为参数的函数。

我想做的如下:

myCSVfunction <- function(.csv){
  headVal<-head(.csv)
  string("The head of the dataset is: %d",headVal)

在完成功能制作后,我希望它做以下事情:

>myCSVfunction(C:/Path/file.csv)
>The head value of the dataset is:
...("Head" of the data here)...

请注意,我在发布之前尝试了很多谷歌搜索并自己尝试了一些随机试验。

谢谢。

【问题讨论】:

标签: r function csv


【解决方案1】:

你必须读取 R 中的 csv,否则它不知道它在看什么,你也应该将文件作为字符串传递给函数。

myCSVfunction <- function(.csv) {
    csv <- read.csv(.csv)
    headValue <- head(csv)
    print("The head of the dataset is:")
    return(headValue) # or print(headValue) if you prefer
}

例如:

write.csv(mtcars, "mtcars.csv", row.names = FALSE)
myCSVfunction("mtcars.csv")
#[1] "The head of the dataset is:"
#mpg cyl disp  hp drat    wt  qsec vs am gear carb
#1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

【讨论】:

  • 你说我读了文件,但你使用的是 write.csv;我不能使用 read.csv 吗?
  • 对不起,我使用write.csv(),以便我可以任意创建一个csv文件来测试myCSVfunction。如果您查看myCSVfunction 的定义方式,它会接受参数并调用read.csv
  • 所以,如果我做 read.csv(tips, "C:/path/tips.csv", row.named = FALSE) 和做 myCSVfunction("tips.csv"),会不会工作吗?
  • 它正在工作。非常感谢。非常感谢您的帮助。
  • 我认为最好查看这些功能的帮助文档。我不认为他们做你认为他们做的事。 ?write.csv?read.csv
最近更新 更多