71672

“NAs are not allowed in subscripted assignments”

I have a data frame with some missing values that I want to take from anther date frame and insert into the first. This works when the values I want to supplement miss in all rows of the first data frame.

Here is a working exaxmple:

dat <- data.frame(code = c("A11", "B22"), age = c(NA, NA), sex = c(NA, NA), more = c(7, 4), stringsAsFactors = FALSE) age.and.sex <- read.table(textConnection(" code age sex A11 15 m B22 10 f "), header = TRUE, stringsAsFactors = FALSE) dat$sex[match(dat$code, age.and.sex$code)] <- age.and.sex$sex dat$age[match(dat$code, age.and.sex$code)] <- age.and.sex$age dat code age sex more 1 A11 15 m 7 2 B22 10 f 4

The problem is that when I the values are not missing from all rows in the firest data frame, but I need to supplement only certain rows, I get an error.

Here is an example that does not work:

dat <- data.frame(code = c("A11", "B22", "C33"), age = c(NA, NA, 12), sex = c(NA, NA, "m"), more = c(7, 4, 9), stringsAsFactors = FALSE) age.and.sex <- read.table(textConnection(" code age sex A11 15 m B22 10 f "), header = TRUE, stringsAsFactors = FALSE) dat$sex[match(dat$code, age.and.sex$code)] <- age.and.sex$sex Error in dat$age[match(dat$code, age.and.sex$code)] <- age.and.sex$age : NAs are not allowed in subscripted assignments dat$age[match(dat$code, age.and.sex$code)] <- age.and.sex$age Error in dat$age[match(dat$code, age.and.sex$code)] <- age.and.sex$age : NAs are not allowed in subscripted assignments

I do not understand the error that R returns.

How do I need to change my code to get this to work again?

The result I'm trying to achieve is:

dat code age sex more 1 A11 15 m 7 2 B22 10 f 4 3 C33 12 m 9 <hr>

Thank you all for your help so far. But I must admit that I'm not quite happy with your solutions.

What you suggest is a four step approach: add one data frame to the other, move the values to their desired destination one by one, then delete the now superfluous secondary columns. As a schema, your solution looks something like this:

<img src=https://www.e-learn.cn/content/wangluowenzhang/"https://i.stack.imgur.com/u3CC7.png" alt="enter image description here">

That seems awfully complicated to me!

When I look at my data, the solution that seems obvious to me has only one step: cut the "matrix" from one data frame and paste it into the "empty" area of the other data frame. Here is what it looks like in my mind:

<img src=https://www.e-learn.cn/content/wangluowenzhang/"https://i.stack.imgur.com/qbTj1.png" alt="enter image description here">

And apparently that is actually possible:

dat[1:2,2:3] <- age.and.sex[1:2,2:3] dat code age sex more 1 A11 15 m 7 2 B22 10 f 4 3 C33 12 m 9

This, of course, only works if both data frames are ordered in the same way. Which is why I used match(), which overcomes the problem when the rows aren't ordered – but fails when the number of rows is not the same.

<strong>Or is there a way to match(), even if the number of rows is not the same?</strong>

Answer1:

You're trying to assign to these three rows:

> match(dat$code, age.and.sex$code) [1] 1 2 NA

because dat$code and age.and.sex$code are not the same length, so the third comparison is NA.

I'm not sure what you actually mean to be matching, but you might just try subsetting to the first two observations, or na.omit, etc.

But a better way to join data from two tables is to use a join.

library(data.table) dat <- data.table(dat) setkey(dat,code) age.and.sex <- data.table(age.and.sex) setkey(age.and.sex,code) dat[age.and.sex] > dat[age.and.sex] code age sex more i.age i.sex 1: A11 NA m 7 15 m 2: B22 NA f 4 10 f

Note how the columns of the inner table get appended to those of the outer table.

<strong>More...</strong> Per @joran's suggestion...you can use this technique to fill in missing observations:

joined <- dat[age.and.sex] joined[is.na(age),age:=i.age] #only replace the value missing from left table joined[,c("i.age","i.sex"):=NULL] joined > joined code age sex more 1: A11 15 m 7 2: B22 10 f 4

<strong>Update</strong> to address your comment...just reverse the join. There are some cleverer ways to do this less manually, but this should be simple to follow:

joined <- age.and.sex[dat] joined[is.na(age),age:=i.age] joined[is.na(sex),sex:=i.sex] joined[,c("i.age","i.sex"):=NULL] > joined code age sex more 1: A11 15 m 7 2: B22 10 f 4 3: C33 12 m 9

If this technique is to your liking you should definitely read ?data.table and the related vignette to learn more about joins.

Recommend

  • Convert cell array columns into matrix columns
  • How to store only upto 4 decimal places in a matlab variable?
  • How to Superscript some Text in a TextBox/TextBlock Control in windows phone 8?
  • Adding 0's to cell array such that each column contains an equal number of entries - MATLAB
  • Multi line title in push notification for iOS
  • Replace values with numbers
  • rvest package - Is it possible for html_text() to store an NA value if it does not find an attribute
  • Sending commands to stdin and sending end of transmit (Ctrl+D)
  • R: merging copies of the same variable
  • MATLAB Combine matrices of different dimensions, filling values of corresponding indices
  • Add a div to replace Video after Video Plays Through
  • Is there a limit on how long a cfquery with cfqueryparam can get?
  • oracle row contention causing deadlock errors in high throughtput JMS application
  • WPF Animation doesn't run first time
  • How to clear specified format data from clipboard?
  • ValueError: Found arrays with inconsistent numbers of samples
  • Firefox extension testing and developing - I'm confused
  • Read a file in “chunks” using PHP
  • Django AWS S3 Invalid certificate when using bucket name “.”
  • How do i disable a text box within an iframe
  • How to remove single character words from string with preg_replace
  • How does inheritance and polymorphism work in this situation?
  • BackgroundTransferRequest WP7
  • Leaflet z-index
  • Deduce parent class of inherited method in C++
  • Haskell: function composition with anonymous/lambda function
  • What's the name of this finding square root algorithm?
  • auth.provider is not set to 'password' when user signs-in with email and password
  • C function strchr - How to calculate the position of the character?
  • How to use tag-it
  • How can I extend PHP DOMElement?
  • why calling cd shell command through system() or execvp() from a child process won't work?
  • Can I programmatically choose the Android layout folder?
  • Redux Form - Not able to type anything in input
  • Insert new calendar with SyncAdapter- Calendar API Android
  • MonoTouch: How to download pdf incrementally as indicated in the Apple slides “Building Newsstand Ap
  • Installing Apache MyFaces 2 on WildFly 8.2.0
  • Using jQuery closest() method with class selector
  • Array.prototype.includes - not transformed with babel
  • Why can't I rebase on to an ancestor of source changesets if on a different branch?