Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 211985

mapply giving non-numeric argument to binary operator error in R

$
0
0

I am trying to generate a variable flagging implausible age differences between respondents and their parents in a household roster. I have two issues i) my function does not replace the flag variable with TRUE when it should, ii) mapply gives an error on " non-numeric argument to binary operator error" while I don't get this error when I apply the function on only two columns. Novice in R, any help is very much appreciated. Below, I tried to make a reproducible example.


# Variables
respbirth <- c(1974, 1950, 1990, 1980 ) 
B1010_1 <- c(1950, 1960, 1960, 1979 ) 
B1040_1 <- c(3,3,3,3)
B1010_2 <- c(1974, NA, NA, 1975 ) 
B1040_2 <- c(3,1,3,3)

# Data frame
df <- data.frame(respbirth, B1010_1, B1040_1, B1010_2, B1040_2 ) 
df

# Generate empty variable for flaging cases
df$flag_parent <- FALSE

## Generate a function flagging implausible differences using year of birth
attach(df)  # the function doesnt work without this for some reason
imp.parent <- function(data=df,parentAge=B1010_1,relationship=B1040_1) {
  df$flag_parent <- with(df, ((respbirth-parentAge)<18) & (relationship==3))
return(df)
}

# Test
df <- imp.parent(parentAge=B1010_1,relationship=B1040_1)

# Apply this function to all columns
parentAge <- c(paste0("B1010_",1:19, sep=""))
relationship <- c(paste0("B1040_",1:19, sep=""))
mapply(imp.parent, parentAge, relationship )


Viewing all articles
Browse latest Browse all 211985

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>