简体   繁体   中英

function applied to dataset R

Below are two dataframes labeled as 'A' and 'C'. I have created a function that would take the top 5 rows for dataframe and want the same applied to dataframe C. However, it only replicates it for A. How would I have this function be applied for C only. Thanks!

    L3 <- LETTERS[1:3]
    fac <- sample(L3, 10, replace = TRUE)
    (d <- data.frame(x = 1, y = 1:10, fac = fac))
    ## The "same" with automatic column names:
    A<-data.frame(1, 1:10, sample(L3, 10, replace = TRUE))

    L3 <- LETTERS[7:9]
    fac <- sample(L3, 10, replace = TRUE)
    (d <- data.frame(x = 1, y = 1:10, fac = fac))
    ## The "same" with automatic column names:
    C<-data.frame(1, 1:10, sample(L3, 10, replace = TRUE))

    function_y<-function(Data_Analysis_Task) {
       sample2<-head(A, 5)
       return(sample2)
    }

    D<-function_y(C)

We need to have the same argument passed inside the function as well

function_y <- function(Data_Analysis_Task) {
      head(Data_Analysis_Task, 5)

 }

 D <- function_y(C)

If we use head(A, 5) , inside the function, it looks for the object 'A', inside the function env first, then if it doesn't find, looks at the parent env, and so on until it finds the object 'A' in the global env. So, it would return the same output of head of 'A' every time the function is called

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM