Laura
Laura

Reputation: 177

How do I insert the value from another column?

I want to fill a cell with a value from another column on the corresponding row.

I get the error message

Warning message:
In ukDataTest$s[is.na(ukDataTest$s) & !is.na(ukDataTest$s_2013)] <- ukDataTest$s_2013 :
  number of items to replace is not a multiple of replacement length

When I run:

ukDataTest$s[is.na(ukDataTest$s) & !is.na(ukDataTest$s_2013)] <- ukDataTest$s_2013

I presume this is because I am in effect assigning a whole column of values.

I want to assign the value on the corresponding row from ukDataTest$s_2013.

How do I do this?

Example data:

library(dplyr)
number <- c(1,2,3,4,5)
s <- c(0.1,NA,0.5,NA,0.8)
s_2013 <- c(NA,0.3,NA,0.7,NA)
cbind(number,s,s_2013)

Upvotes: 0

Views: 42

Answers (2)

Joseph Clark McIntyre
Joseph Clark McIntyre

Reputation: 1094

You are correct about the reason for the error. The solution is to only try to replace with the corresponding rows from the other column, as in

ukDataTest$s[is.na(ukDataTest$s) & !is.na(ukDataTest$s_2013)] <- ukDataTest$s_2013[is.na(ukDataTest$s) & !is.na(ukDataTest$s_2013)]

Here's an example with some toy data

> dat <- data.frame(col1 = c(2, NA, 3, NA, 1, 1, NA, NA), 
+                   col2 = c(1, 1, NA, 2, 2, NA, NA, 4))
> 
> dat$col1
[1]  2 NA  3 NA  1  1 NA NA
> 
> dat$col1[is.na(dat$col1) & !is.na(dat$col2)] <- dat$col2[is.na(dat$col1) & !is.na(dat$col2)]
> 
> dat$col1
[1]  2  1  3  2  1  1 NA  4

Alternately, with the data that you posted in your question.

> number <- c(1,2,3,4,5)
> s <- c(0.1,NA,0.5,NA,0.8)
> s_2013 <- c(NA,0.3,NA,0.7,NA)
> 
> dat <- data.frame(number, s, s_2013)
> 
> dat$s[is.na(dat$s) & !is.na(dat$s_2013)] <- dat$s_2013[is.na(dat$s) & !is.na(dat$s_2013)]
> 
> dat$s
[1] 0.1 0.3 0.5 0.7 0.8

Upvotes: 1

user34018
user34018

Reputation: 223

Now they are the same size, and the whenever is.na(ukDataTest$s) & !is.na(ukDataTest$s_2013) is true, the corresponding row value of column s_2013 will be assigned to s.

    ukDataTest$s[is.na(ukDataTest$s) & !is.na(ukDataTest$s_2013)] <- ukDataTest$s_2013[is.na(ukDataTest$s) & !is.na(ukDataTest$s_2013)]

Upvotes: 0

Related Questions