I am trying to run a very easy code within a function but despite the return statement, I get the following error:
Error in
$<-.data.frame
(*tmp*
, column_name, value = character(0)) : replacement has 0 rows, data has 56 <
I am working with a 20x3 df, in which I want to replace certain values by new values as specified by the function below:
# Create a reproducible data frame called df_old in which I want to perform changes on the variable type
df_old = set.seed(42)
n <- 6
df_old <- data.frame(id=1:n,
date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
group=rep(LETTERS[1:2], n/2),
age=sample(18:30, n, replace=TRUE),
type=factor(paste("type", 1:n)),
x=rnorm(n))
df_old
# id date group age type x
# 1 1 2020-12-26 A 27 type 1 0.0356312
# 2 2 2020-12-27 B 19 type 2 1.3149588
# 3 3 2020-12-28 A 20 type 3 0.9781675
# 4 4 2020-12-29 B 26 type 4 0.8817912
# 5 5 2020-12-30 A 26 type 5 0.4822047
# 6 6 2020-12-31 B 28 type 6 0.9657529
# Create a function
f.rename.values <- function(df, column_name, old_value, new_value){
df$column_name[file$column_name == old_value] <- new_value
return(df)
}
# Call function to change values in the column called type in df_old
type = df_old$type
df_new <- f.rename.values(df_old, type, 3, other_type)
Here are my questions:
- Why does R throw an error?
- Why does R return df_new that is the same as df_old