Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Converting missing values into 0 for some columns with conditions

    Dear community members,

    I would like to convert NA values (.) into 0 if a column (variable) contains no 0 value at all across whole observations for some columns. So, my logic is like this:

    1. I am going to use a for loop so that this task is repeated from “n”th column to “p”th column.
    2. For each column in range, I would like to use two pieces of information. The first is whether a column has at least one 0 value. If Yes, all missing values should remain as it is. Here is a second thing. If not, I would like to convert missing values to 0s in that specific column.
    3. I would like to repeat it for “p-n+1” times, meaning from column "p" to column "n".

    Here are my detailed questions:
    1. Is there any way to access “n”th column from dataset? For example, in R, we can access by entering dataset[ , n].
    2. As for replacement procedure, I would like to use the one like this: replace Varname = 0 if (count if Varname == 0) == 0 & Varnmae == . But, obviously it is not working. It seems that Stata is not supporting the feature to use a result of value, such as count if Varname == 0 as a condition. Would there be a way to handle this issue?

    To help you better understand my situation and for the users who is familiar with R and Stata, I attached my lines of codes for R.

    for (i in n:p) { * The for loop for each variable
    for (j in 1:nrow(dataset) { * The for loop for each observation in a specific variable
    if (sum(dataset[ , i] == 0) == 0 & dataset[j, i] == .) {
    data[j, i] = 0} else {
    data[j, i] = data[j, i]
    }
    }

    Any advice would be greatly appreciated.
    Last edited by John Charlse Doe; 20 Nov 2022, 11:02.

  • #2
    My apology here. I think it is posted on Mata thread though mine should have been posted on General thread. So, I have made a duplicate question in General thread. Please ignore this.

    Comment

    Working...
    X