Home > Enterprise >  R: Assigned data `*vtmp*` must be compatible with existing data error
R: Assigned data `*vtmp*` must be compatible with existing data error

Time:01-10

I'm new to R with experience in other typical languages and having trouble with creating some functions. I'm getting this error:

Error: Assigned data `*vtmp*` must be compatible with existing data.
x Existing data has 5114 rows.
x Assigned data has 0 rows.
i Only vectors of size 1 are recycled

Here is the code. Any one know how to fix this?

print("***********************************************************************************")
#Load the packages
library(descr)
library(Hmisc)
library(ggplot2)
#Load AddHealthIV Dataset
data<-addhealth4
########################Functions########################################
missingDatatoNA <- function(variable, Missing) {
  for(i in 0:3){
    data$variable[data$variable==3]<-NA
  }
    return(data$variable)
}
####################Explanatory Variables################################
#o = openness to experience, c = conscientiousness, a = etc.
#will eventually make a master secondary variable for each trait
#* indicates necessity for reversal of codes
data$e1<-data$H4PE1 #*
data$e1<-missingDatatoNA(data$e1, c(6,8,"."))

Here is the link to the data set: https://drive.google.com/file/d/1wTtvsilxR9-RjPPVEFg_tgbBc8MTeG6i/view?usp=sharing

It's from my psych stats class, you can trust it, I don't know how else to safely share it.

CodePudding user response:

As you pass a vector data$e1 to your function there is no need for data$variable. Actually data$variable is NULL as there is (probably) no column with name variable in your dataset data. That's why you get the error.

This could be illustrated using mtcars as example data which besides some warnings results in the same error message you reported:

# Reproduce the issue
data <- tibble::as_tibble(mtcars)

missingDatatoNA <- function(variable, Missing) {
  for (i in 0:3) {
    data$variable[data$variable == 3] <- NA
  }
  return(data$variable)
}
data$e1 <- data$hp
missingDatatoNA(data$e1, c(6, 8, "."))
#> Warning: Unknown or uninitialised column: `variable`.

#> Warning: Unknown or uninitialised column: `variable`.
#> Error: Assigned data `*vtmp*` must be compatible with existing data.
#> x Existing data has 32 rows.
#> x Assigned data has 0 rows.
#> ℹ Only vectors of size 1 are recycled.

To fix your issue could simply do variable[variable==3] <- NA:

# Solve the issue
missingDatatoNA_fixed <- function(variable, Missing) {
  for (i in 0:3) {
    variable[variable == 3] <- NA
  }
  return(variable)
}
missingDatatoNA_fixed(data$e1, c(6, 8, "."))
#>  [1] 110 110  93 110 175 105 245  62  95 123 123 180 180 180 205 215 230  66  52
#> [20]  65  97 150 150 245 175  66  91 113 264 175 335 109
  •  Tags:  
  • Related