从 4 个变量创建一个列

Creating a single column from 4 variables

我的数据针对每个制裁年度的制裁。有 5 种类型的定向制裁,但由于我有兴趣查看整体制裁而不是它们的具体类型,我想创建一个新列来表示在给定年份是否实施了总体定向制裁。

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

我希望它看起来像下面这样:

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

我怎么能得到这个?谢谢

您可以对涉及 5 种类型的 Sanctions 的列进行按行求和 (rowSums) 并检查是否施加了任何制裁,然后使用 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

您还可以使用 cbindapplyifelse 的组合:

cbind(df1[,c(1,7)], Sanctions=apply(df1[,2:6], 1, function(x) {
    ifelse(any(x==1), 1, 0)
}))

 Country Year Sanctions
 Angola  1993 1        
 Angola  1994 1        
 Angola  1995 1

正如@Bazz 所建议的,可以通过执行以下操作缩短此时间:

cbind(df1[,c(1,7)], Sanctions=as.numeric(apply(df1[,2:6], 1, any)))

这里,列是按索引号而不是按名称选择的。但如果您愿意,您可以轻松地按名称获取列。

希望对您有所帮助。

您可以使用 dplyr,结果命令传达了您想要实现的目标:

library(dplyr)
df1 %>% group_by(Country, Year) %>% 
        mutate(Sanctions = as.numeric(any(Asset_freeze, Sectoral, Commodity, Diplomatic, Individual))) %>% 
        select(Country, Year, Sanctions)
##  Country   Year Sanctions
##   <fctr> <fctr>     <dbl>
##1  Angola   1993         1
##2  Angola   1994         1
##3  Angola   1995         1

我们可以对 2:6 列使用 pmax,它应该会自动选取最大值

cbind(df1[c("Country", "Year")], Sanctions = do.call(pmax, df1[2:6]))
#    Country Year Sanctions
#1  Angola 1993         1
#2  Angola 1994         1
#3  Angola 1995         1

使用data.table:

require(data.table)

setDT(df1)

NSanc <- 5L

df1[, list(Sanctions = do.call(any, .SD)),
    by = c("Country", "Year"),
    .SDcols = 2:(NSanc + 1)]

NSanc 是制裁类型的数量。