Replacing NA values of a column using values from another column
2
0
Entering edit mode
8 months ago
SGMS ▴ 70

Hi guys,

I am trying to manipulate my dataset but I have two conditions and I haven't dealt with such an issue before.

For example I have:

 ID  T   value(%)   H1   sex     H2

1   T1    38.1     15.2    F    14.5

1   T2    39.5     14.2    M    14.5

10  T1    34.1      N      F    11.4

I want to replace the NA value of H1 column, with the value in the corresponding H2's row (11.4). I have previously merged datasets based on the ID so H1 and H2 are sorted based on ID. When I try to replace the NA value of H1 with the values in H2, it says "Error in $<-.data.frame(*tmp*, H1, value = c(14.5, 14.1, : replacement has 298 rows, data has 609".

So I guess my problem is that I want to replace my NA values using another column's rows. Is there a way of doing this?

Any help would be greatly appreciated.

Thank you in advance

data manipulation R • 1.0k views
ADD COMMENT
2
Entering edit mode
8 months ago
Sam ★ 3.6k

If you have data.table installed, and assuming your data is stored in dat

library(data.table)
dat <- as.data.table(dat)
dat[is.na(H1), H1:=H2]

should do

ADD COMMENT
0
Entering edit mode
8 months ago
Hamid Ghaedi ★ 1.5k

Say your data frame is df using base R you can do:

df[is.na(df$H1), ]$H1 <- df[is.na(df$H1), ]$H2

Or using ifelse:

enter image description here

ADD COMMENT

Login before adding your answer.

Traffic: 2113 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6