我正在尝试使用rowwise()
和dplyr
在数据框的每一行上运行一个函数,方法是将每一行作为列表传递给函数,然后使用列名来访问变量。
下面的代码显示了我正在尝试做的事情。代码将整个数据帧传递给函数,它不会遍历每一行。有什么建议吗?
#initial dataframe
df <- data.frame(X=c(10,22,43,47,15), Y=c(2,3,4,2,2))
## cumbersome version - pass each variable
dfResult <- df %>%
rowwise() %>%
mutate(Z=FnAdd(X,Y)) %>%
mutate(K=FnMult(X,Y,Z))
FnAdd <- function(X,Y){
R <- c()
for(i in 1:4){
R[i]=X+i*Y
}
return (list(R))
}
FnMult <- function(X,Y,Z){
R <- c()
for(i in 1:4){
R[i]=X+i*Y*2*Z[i]
}
return (list(R))
}
##concise version - just pass a list of each row
#code runs but is incorrect - it always uses the first row
dfResultX <- df %>%
rowwise() %>%
mutate(Z=FnAddX(as.list(dfResult))) %>%
mutate(K=FnMultX(as.list(dfResult)))
#function should receive a list of one row
#actually receives list of whole data frame
FnAddX <- function(Vars){
R <- c()
for(i in 1:4){
R[i]=Vars$X+i*Vars$Y
}
return (list(R))
}
#ditto
debug(FnMultX)
FnMultX <- function(Vars){
R <- c()
for(i in 1:4){
V1 <- Vars$X
V2 <- Vars$Y
#next line of code is wrong and crashes function
V3 <- Vars$Z[1][i]
R[i]=Vars$X+i*Vars$Y*2*Vars$Z[i]
}
return (list(R))
}
#loop option
#not ideal but could work if dplyr won't
Result <- c()
for(i in 1:nrow(df)){
RowList <- as.list(df[i,])
NewVec <- FnAddX(RowList)
Result <- append(Result,NewVec)
}
#bind result to original data frame
#code not working - not sure how to do this
dfResultX <- df %>%
as.data.frame(Result)