Create a dummy variable based on two variables x1 and x2 (dummy=x1 only if at least one adjacent x2=yes)

Advertisements Below is the code to generate the dataframe for demonstration: d<-data.frame(x1=c(rep("no",5),rep("yes",4),rep("no",2),rep("yes",3),rep("no",2),rep("yes",3)), x2=c(rep("no",6),rep("yes",1),rep("no",9),rep("yes",2),rep("no",1)), dummy=c(rep(0,5),rep(1,4),rep(0,5),rep(0,2),rep(1,3))) I have two variables x1 and x2. What I want is a dummy variable, named as ‘dummy’, based on both x1 and x2 indicators. Specifically, the dummy should equal 1 by capturing all x1=yes values conditional that at least one of… Read More Create a dummy variable based on two variables x1 and x2 (dummy=x1 only if at least one adjacent x2=yes)

How to create a Dummy Variable in Python if Missing Values are included?

Advertisements How to create a dummy variable if missing values are included? I have the following data and I want to create a Dummy variable based on several conditions. My problem is that it automatically converts my missing values to 0, but I want to keep them as missing values. import pandas as pd mydata… Read More How to create a Dummy Variable in Python if Missing Values are included?

Creating a dummy variable based on whether words appear in multiple columns

Advertisements I’m working with a large df on cross-national time-series protest patterns. I would like to create a dummy variable based on whether one or a select group of words appears in any of those columns. I have included data below. Here’s verbally what I want to do: If the phrases (1) political behavior (2)… Read More Creating a dummy variable based on whether words appear in multiple columns

Replace NAs with zeros using ifelse

Advertisements I am trying to replace NAs in my variable- called violence- with zeros and create a new dummy variable using ifelse. The violence variable has several categories and NAs. The category ignore should be coded 1 but other categories including NAs should be coded 0. I use the following code: df$new_variable<-ifelse(is.na(df$violence)=="ignore",1,0) However, the code… Read More Replace NAs with zeros using ifelse