[英]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.我有一个用户定义的 function,我想在 dataframe 的所有行中使用它。 I've tried using the apply() function to accomplish this but I do not think my syntax is correct.我尝试使用 apply() function 来完成此操作,但我认为我的语法不正确。 I've also tried to make another user-defined function to accomplish this, but it been creating errors.我还尝试制作另一个用户定义的 function 来完成此操作,但它一直在创建错误。 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.但是,在最小的可重现示例中,我确实注意到“结果” dataframe 中的变量的 class 都是字符,我希望其中一些是双倍的。 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.我们可以使用mapply/Map
- apply
转换到matrix
,矩阵只能有一个 class。 So, we use Map/mapply
to loop over each of the columns and apply the function on the corresponding elements因此,我们使用Map/mapply
循环遍历每一列,并在相应的元素上应用 function
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.