r - 根据两列中的信息向我的数据框添加一列
问题描述
我想根据数据框两列中的信息向我的数据框添加一列。
在我的示例数据框中,我有一个样本的两行条目,它们是第 3 行和第 4 行。我想编写一个新列“main”并在每行填充“1”的代码,该行具有唯一的标签号。对于具有重复标签编号的行,我需要权重最高的行在 main 中为“1”,所有其他行都用“0”填充。
df
sp weight tag
1 green 70 1
2 yellow 63 2
3 red 41 3
4 red 25 3
5 red 9 3
df with "main" column added
sp weight tag main
1 green 70 1 1
2 yellow 63 2 1
3 red 41 3 1
4 red 25 3 0
5 red 9 3 0
这是我到目前为止所拥有的:
df$is.uniq <- duplicated(df$tag) | duplicated(df$tag), fromLast = TRUE)
df$main <- ifelse(is.uniq==TRUE, "1", ifelse(is.uniq==FALSE, "0", NA ))
我知道我需要更改第二个 ifelse 语句以引用权重列,并为最大权重填写 1,为其他所有内容填写 0,但我还没有弄清楚如何做到这一点。
解决方案
我们可以按操作创建一个组,并使用max
“权重”在逻辑条件下创建二进制文件
library(dplyr)
df %>%
group_by(sp) %>%
mutate(main = +(weight == max(weight)))
-输出
# A tibble: 5 x 4
# Groups: sp [3]
# sp weight tag main
# <chr> <int> <int> <int>
#1 green 70 1 1
#2 yellow 63 2 1
#3 red 41 3 1
#4 red 25 3 0
#5 red 9 3 0
或者在base R
一个选项中,首先order
按“权重”按降序排列数据,然后应用duplicated
dfnew <- df[order(df$sp, -df$weight),]
dfnew$main <- +(!duplicated(dfnew$sp))
数据
df <- structure(list(sp = c("green", "yellow", "red", "red", "red"),
weight = c(70L, 63L, 41L, 25L, 9L), tag = c(1L, 2L, 3L, 3L,
3L)), class = "data.frame", row.names = c("1", "2", "3",
"4", "5"))
推荐阅读
- php - PHP 执行时间:如何使用 symfony 系统测量
- android - 科尔多瓦构建 minsdkversion 错误
- android - React Native + Android:为什么我会收到此消息“:app:processDebugResources FAILED”以及如何解决?
- wordpress - 将子文件夹重定向到 WordPress 中的新文件夹
- java - HttpRequestException:无法在 Android Studio 3.1.1 中发出警告(但同步成功)
- javascript - 如何获取 Observable Array 属性的唯一值 - Angular
- java - 如何在 Eclipse 项目(Java)中永久包含外部库?因此,当将其移植到另一台计算机时,它仍然存在
- python - 如何输入具有可变输入数据长度的 Scikit 学习 MLP 分类器。
- javascript - CakePHP 中的 Ajax 菜单
- git - git list 删除了整个 repo 历史中的文件