我有以下数据集:
clubs <- c("AZ","AZ","AZ","AZ")
won <- c("W","L","W","L")
last_match <- c("NA", "NA", "NA","NA")
df_new <- data.frame(clubs, won, last_match)
我现在想做的是:
以下代码可以正常使用:
calc <- function(){
setwd("...")
df_new <- read.csv2("df_club.csv", header = T)
#checking
print(head(df_new))
for(i in 2:nrow(df_new)){
df_new$last_match[i] <- df_new$won[i-1]
}
#checking
print(head(df_new))
}
出于概述目的,我想将计算部分放在不同的函数中。这就是我尝试这个的原因:
#define calculating formule
calculate_last_win <- function(df){
for(i in 2:nrow(df_new)){
df_new$last_match[i] <- df_new$won[i-1]
}
return(df)
}
#normal function
calc <- function(){
setwd("...")
df_new <- read.csv2("df_club.csv", header = T)
#checking
print(head(df_new))
calculate_last_win(df_new)
#checking
print(head(df_new))
}
但是我的输出没有变化。对于出了什么问题的任何想法?
答案 0 :(得分:0)
在calc
中,将行calculate_last_win(df_new)
替换为df_new <- calculate_last_win(df_new)
,在函数calculate_last_win
中,将df_new
替换为df
。
clubs <- c("AZ","AZ","AZ","AZ")
won <- c("W","L","W","L")
dfNew <-data.frame(clubs, won)
#define calculating formule
calculate_last_win <- function(df){
for(i in 2:nrow(df)){
df[i,"last_match"] <- df[i-1,"won"]
}
return(df)
}
#normal function
calc <- function(){
setwd("...")
df_new <- dfNew
#checking
print(head(df_new))
df_new <- calculate_last_win(df_new)
#checking
print(head(df_new))
return ( df_new )
}
> calc()
clubs won
1 AZ W
2 AZ L
3 AZ W
4 AZ L
clubs won last_match
1 AZ W <NA>
2 AZ L W
3 AZ W L
4 AZ L W
clubs won last_match
1 AZ W <NA>
2 AZ L W
3 AZ W L
4 AZ L W
答案 1 :(得分:0)
我认为你的功能应该是这样的。该函数需要df_new
为df
。
calculate_last_win <- function(df){
for(i in 2:nrow(df)){
df$last_match[i] <- df$won[i-1]
}
return(df)
}
在调用函数后,我还会检查return(df)
是否正在替换df_new
。