gpt4 book ai didi

r - 从 4 个变量创建单列

转载 作者:行者123 更新时间:2023-12-04 11:43:21 25 4
gpt4 key购买 nike

我的数据针对每个制裁年度都有针对性的制裁。定向制裁有 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

我怎么能得到这个?谢谢

最佳答案

您可以按行求和( rowSums )涉及 Sanctions 5 种类型的列并检查是否施加了任何制裁,然后使用 as.numeric 将 bool 值转换为数字

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

关于r - 从 4 个变量创建单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39098982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com