Reputation: 314
I'm trying to write a function that fills empty values with the value "N," but I'm getting the following error. Could someone assist me in resolving this problem?
Error
Error in .subset2(x, i, exact = exact) : no such index at level 1
R Code
library(tidyr)
# create data frame
distance<-c('a','b','c', 'd')
area<-c(11,12,13, "")
type<-c('typea', 'typeb', 'typec', "")
# check data.frame
my.df<-data.frame(distance, area, type)
my.df$area
fillvalues<-function(columName, value){
my.df[[columName]] <- sub("^$", Value , my.df[[columName]])
print(my.df)
}
print(fillvalues(area, N))
Upvotes: 1
Views: 735
Reputation: 887251
Using tidyverse
library(dplyr)
library(stringr)
fillvalues<-function(columnName, value){
my.df %>%
mutate({{columnName}} := str_replace({{columnName}},
"^$", rlang::as_string(ensym(value))))}
-testing
> fillvalues(area, N)
distance area type
1 a 11 typea
2 b 12 typeb
3 c 13 typec
4 d N
Upvotes: 1
Reputation: 124438
To make your code work, make use of quotes when calling your function. Additionally, inside your function it should be value
instead of Value
:
fillvalues <- function(columName, value){
my.df[[columName]] <- sub("^$", value , my.df[[columName]])
my.df
}
fillvalues("area", "N")
#> distance area type
#> 1 a 11 typea
#> 2 b 12 typeb
#> 3 c 13 typec
#> 4 d N
Upvotes: 1