简体   繁体   中英

How do I correctly pass data from a dataframe into a function?

I have a user-defined function that I would like to use across all rows in a dataframe. I've tried using the apply() function to accomplish this but I do not think my syntax is correct. I've also tried to make another user-defined function to accomplish this, but it been creating errors. I tried to make a minimal reproducible example of the error but it does not seem to have the same problem as my actual code. However, in the minimal reproducible example, I did notice that the class of the variables in the "result" dataframe are all character and I would expect some of them to be doubles. I'm hoping that at least correcting this issue in the example code will help me to figure out the problem in the actual code.

Any advice on a good way to do this would be appreciated.

library(tidyverse)

function1 <- function(cut, depth, price){
    result <- data.frame(cut = character(),
                        depth = double(),
                        price = double(),
                        new_value = double(),
                        new_char = character())
    
    new_value <- depth*price
    new_char <- paste0(cut, "kjh", as.character(depth))
    
    result[nrow(result) + 1,] <- c(cut, depth, price, new_value, new_char)
    
    print(result)
}

#use function with variables
function1("good", 100, 3) 

#use function on all rows in a dataframe
df <- head(diamonds)

function2 <- function(){
  for(i in 1:nrow(df)) {
    row <- df[i,]
    #function1 on each row
   function1(row$cut, row$depth, row$price)
 }
}

function2()

#how to use apply function?
apply(df, 1, function1(cut, depth, price))

We could use mapply/Map - apply converts to matrix and matrix can have only a single class. So, we use Map/mapply to loop over each of the columns and apply the function on the corresponding elements

do.call(rbind, Map(function1, df$cut, df$depth, df$price))

-output

cut depth price new_value         new_char
1   5  61.5   326     20049     Idealkjh61.5
2   4  59.8   326   19494.8   Premiumkjh59.8
3   2  56.9   327   18606.3      Goodkjh56.9
4   4  62.4   334   20841.6   Premiumkjh62.4
5   2  63.3   335   21205.5      Goodkjh63.3
6   3  62.8   336   21100.8 Very Goodkjh62.8

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