Pragyaditya Das Pragyaditya Das - 2 months ago 6
R Question

Want to write a function that takes a csv file as an argument

I am trying to write a function that would take a csv file as an argument.

What I am trying to do is as follows:

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


In completion of the function making, I want it to do do the following:

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


Please note that I tried doing a lot of Googling and tried some random trials myself before posting.

Thank you.

Answer

You have to read the csv in R, or else it doesn't know what it's looking at, also you should probably pass the file into the function as a string.

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
}

For instance:

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
Comments