r - 根据数据框子集中的条件在 R 中添加新列
问题描述
我有以下数据集:
df <- data.frame("attribute"=c('name', 'age', 'location'),
"A"=c(1,0,0), "B"=c(0,1,1), "C"=c(1,0,1))
names(df) <- c("attribute", "A", "B", "C")
df
attribute A B C
name 1 0 1
age 0 1 0
location 0 1 1
- 我想在 R 中添加一个新列,其中包含 A、B C 中的列名之一。
- 条件是属性之一
name, age, location
应与 A、B C 列之一匹配。 属性值为 one 的第一个列名称应作为附加列列出,如下所示:
attribute A B C Column name 1 0 1 A age 0 1 0 B location 0 1 1 B
for(i in df$attribute){for(j in c("A", "B", "C")}print(names(df) [names(df)%in%c("A", "B ", "C")][i]==1)
我无法解决这个问题。
解决方案
我们可以用max.col
df$Column <- names(df)[-1][max.col(df[-1], 'first')]
df$Column
#[1] "A" "B" "B"
推荐阅读
- ios - 优化 Google Map ios sdk 上的许多标记?
- c# - 使用 appsettings 和 IOptions 接口的 .NET 标准库的推荐模式是什么?
- mongodb - Mongoose 播种机:尚未为模型注册模式
- android - 为什么 RxJava 中的 take(5) 运算符返回所有对象
- bash - Kubernetes cron 作业在循环中调用 curl
- javascript - JSON 和 JavaScript 错误
- node.js - node.js 认证中间件
- php - 仅在生产环境中出现的 Vichuploader 问题
- python - 代码生成错误,需要改进
- javascript - 使用 JavaScript 和 HTML5 画布绘制线性函数