1

Hi I have a matrix with 10 values and I would like to replace it in a column of a data frame. I was able to do it with tidyverse and ifelse but the order get all messed up.

data <- data.frame("SN" = 1:10, "Age" = c(NA,15,NA,80,45,NA,90,11,NA,NA), "Name" = c("A","B","C","D","E","F","G","H","I","J"))
newAge <- c(9,5,31,25,65)

data$Age <- ifelse(is.na(data$Age), newAge, data$Age)

The order gets all messed up after the code ran. The replacement is not even correct. Please help!

SN    Age    Name
1      9      A
2      15     B
3      31     C
4      80     D
5      45     E
6      9      F
7      90     G
8      11     H
9      25     I
10     65     J
user11666514
  • 165
  • 1
  • 8

1 Answers1

1

If the number of NA values is same as length of newAge you can directly assign them.

data$Age[is.na(data$Age)] <- newAge
data

#   SN Age Name
#1   1   9    A
#2   2  15    B
#3   3   5    C
#4   4  80    D
#5   5  45    E
#6   6  31    F
#7   7  90    G
#8   8  11    H
#9   9  25    I
#10 10  65    J
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213