想编写一个以csv文件为参数的函数

时间:2016-09-24 18:45:16

标签: r function csv

我正在尝试编写一个将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)...

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

谢谢。

1 个答案:

答案 0 :(得分: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
相关问题