I write this function to generate random numbers in a normal distribution with min, max, mean, sd.
The c argument is column number .
My main problem is that my function seems to work, but the value doesn't replace Tibble
please help me.
Note = each cell of the column has a specific random number.
Note2= "a" variable is a random number
this is code :
ff=function(c,minn,maxx,meann,sdd){
for(i in 1:nrow(continuous_dataset)){
a=round(rtruncnorm(1,minn,maxx,meann,sdd))
continuous_dataset %>% mutate(category = if_else((is.na(continuous_dataset[[i,c]])), a, continuous_dataset[[i,c]]))
}
return(continuous_dataset)
}
Can you show us the first few lines of continuous_dataset?
Because you said that the code worked fine and only the tibble was not changed I paid little attention to the other parts of the function
Because your code is not working as you expect, it is worthwhile to be a little more careful.
E.g. your code overwrites your input: that is okay when the code is working fine but until then I would avoid that because it is not very transparent. I would change the code as follows to make debugging somewhat easier:
I run your code, and a stop sign appears, but I don't have any changes in Tibble.
Is there another way to do my function?
class of continuous_dataset is : [1] "tbl_df" "tbl" "data.frame"
You did not provide a suitable dataset reprex and therefore I made a small version of your continuous_dataset with only one column.
And I adapted the function to replace the column (your version adds a category and overwrites that for each column). See if this works for you:
suppressPackageStartupMessages(
suppressWarnings(
{library(dplyr)
library(truncnorm)
}
)
)
set.seed(2022)
continuous_dataset <- data.frame(
col1 = c(1,NA,3,NA,5)
) %>%
print()
#> col1
#> 1 1
#> 2 NA
#> 3 3
#> 4 NA
#> 5 5
ff=function(df1,colnumber,minn,maxx,meann,sdd){
for(i in 1:nrow(df1)){
a <- round(rtruncnorm(1,minn,maxx,meann,sdd))
# df1=df1 %>% mutate(category = if_else((is.na(df1[[i,colnumber]])), a,df1[[i,colnumber]]))
b <- df1[[i,colnumber]]
df1[[i,colnumber]] <- if_else(is.na(b), a, b)
}
return(df1)
}
continuous_dataset2=ff(continuous_dataset,1,120,150,88,54) %>%
print()
#> col1
#> 1 1
#> 2 124
#> 3 3
#> 4 122
#> 5 5
Created on 2022-03-12 by the reprex package (v2.0.1)