MB92 MB92 - 3 months ago 7
R Question

Creating a single column from 4 variables

My data has targeted sanctions for each sanction year. There are 5 types of targeted sanctions, but as I am interested in looking at the sanctions overall and not their specific type I'd like to create a new column that represents whether overall targeted sanctions are imposed in a given year.

df1 <- data.frame(Country = 'Angola',
Asset_freeze = c(1, 0),
Sectoral = c(1, 0),
Commodity = c(1, 0),
Diplomatic = c(1, 0),
Individual = c(1, 0),
Year = c('1993', '1994', '1995')

Country Asset_freeze Sectoral Commodity Diplomatic Individual Year
(chr) (dbl) (dbl) (dbl) (dbl) (dbl) (int)
1 Angola 0 1 1 0 0 1993
2 Angola 0 1 1 0 0 1994
3 Angola 0 1 1 0 0 1995


I would like it to look like the following:

Country Year Sanctions
(chr) (int) (dbl)
1 Angola 1993 1
2 Angola 1994 1
3 Angola 1995 1


How could i get this? Thanks

Answer

You can rowwise sum(rowSums) the columns involving 5 types of Sanctions and check if any of the sanction is imposed and then convert the boolean values to numeric using as.numeric

cbind(df1[c("Country", "Year")], Sanctions = as.numeric(rowSums(df1[, 2:6]) > 0))


#   Country Year Sanctions
#1  Angola 1993         1
#2  Angola 1994         1
#3  Angola 1995         1
Comments