Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace missing values with calculated values

Tags:

r

missing-data

I'm trying to learn how to replace missing data in one variable with calculated values.

My dataset (bk3) looks like:

ign:  80, 96, 75, 66, 53

Mean: 26, 24, 27, 34, 41

sd:    6,  7, NA,  8,  4

lci:  24, 25, 20, 32, 38

uci:  29, 26, 29, 33, 43

dput:

bk3 <- structure(list(ign = c(80L, 96L, 75L, 66L, 53L), mean = c(26L, 24L, 
  27L, 34L, 41L), sd = c(6L, 7L, NA, 8L, 4L), lci = c(24L, 25L, 20L,
  32L, 38L), uci = c(29L, 26L, 29L, 33L, 43L)), .Names = c("ign",
  "mean", "sd", "lci", "uci"), class = "data.frame", row.names = c(NA, -5L))

Basically, I'm using the 95% confidence intervals (uci, lci) and sample n's (ign) to calculate the missing SDs (sd).

The code I'm trying to use is:

bk3$sd[is.na(bk3$sd)] <- (bk3$uci - bk3$lci) * sqrt(bk3$ign)/3.92

But I'm getting the following warning message:

"number of items to replace is not a multiple of replacement length"

Update: I'm trying to create a function that will do this automatically given the appropriate variables are provided. I've tried setting it up in the following format:

fillsd <- function(x, n, u, l)
{ 
i1 <- is.na(x)
i2 <- n > 59
x[i1 & i2] <- with(df, (u[i1 & i2] - l[i1 & i2]) * (sqrt(n[i1 & 
i2])/3.92)) }

While the function "fillsd" appears to have saved appropriately in my global environment, it doesn't work when I try use it with the following code:

fillsd(x="bk3$sd", n="bk3$ign", u="bk3$uci", l="bk3$lci")

No error message results from that code, but the function didn't appear to do anything either. This is the first function I've worked on, and I haven't been able to find comparable examples to know which part of the code is incorrect. Please let me know if you have any ideas about how to make this work. Thanks!

like image 849
mkpcr Avatar asked Aug 19 '26 09:08

mkpcr


1 Answers

If we replace the NA elements of 'sd' with the corresponding elements of calculated values of other columns, then the logical index should be on both sides of the assignment. Based on the nature of the calculation, it gives a length that equal to the number of rows of the dataset while the lhs is only having less length as we are subsetting only rows that have NA elements which leads to length inequality and thus the error

i1 <- is.na(bk3$sd)
bk3$sd[i1] <- with(bk3, (uci[i1] - lci[i1]) * sqrt(ign[i1])/3.92)

However, if we decide to get a summary based on taking the mean of sum of some columns, it is a single number and it would make sense to not have the logical index on the rhs as the value gets recycled

data

bk3 <- structure(list(ign = c(80, 96, 75, 66, 53), Mean = c(26, 24, 
27, 34, 41), sd = c(6, 7, NA, 8, 4), lci = c(24, 25, 20, 32, 
38), uci = c(29, 26, 29, 33, 43)), .Names = c("ign", "Mean", 
"sd", "lci", "uci"), row.names = c(NA, -5L), class = "data.frame")
like image 81
akrun Avatar answered Aug 21 '26 00:08

akrun