1

I'm having some trouble in editing my data frame. First, my data:

X1 0.7
X2 0.05
X3 0.4
X5 0.9

What I want to do is add a row X4 with 0, so that my data looks like:

X1 0.7
X2 0.05
X3 0.4
X4 0
X5 0.9

I have a large data set, and the missing values are at random places. How do I find the missing values in R to add a row?

1 Answer 1

6

We can use merge with all.x=TRUE. Based on the example provided in the OP's post, we extract the numeric part from the first column using sub, convert to numeric, get the sequence on the range of values and paste with 'X' to create a new 'data.frame'. This will be merged with the old dataset, so that wherever there is no matching values for the first column in the old dataset, the corresponding elements in the second column will be filled by NA. If needed, we can change those to 0 using is.na (but not recommended).

dM <- merge(data.frame(V1=paste0("X", Reduce(`:`, 
   range(as.numeric(sub('\\D+', '', df1$V1)))))), df1, all.x=TRUE)
dM$V2[is.na(dM$V2)] <- 0
dM
#  V1   V2
#1 X1 0.70
#2 X2 0.05
#3 X3 0.40
#4 X4 0.00
#5 X5 0.90
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.