简体   繁体   English

如何使用R从与另一列中的ID相关联的一系列列中仅选择特定的唯一值

[英]How to select only specific unique values from a range of columns which are associated with an ID in another column using R

ID conditionA conditionB conditionC
1    1            0       0
1    0            0       1
1    0            0       0
2    1            0       1
2    0            1       0
3    1            0       1
3    0            1       0
3    1            1       0

in the picture above, I want for each ID only single value of each condition, making it a single row for each ID.在上图中,我希望每个 ID 只有每个条件的单个值,使其成为每个 ID 的一行。 This way I can have one row for each ID and under each condition a 1 or 0. Thanks这样我就可以为每个 ID 分配一行,并且在每个条件下为 1 或 0。谢谢

This can be easily done by using the dplyr package.这可以通过使用 dplyr 包轻松完成。

library(dplyr)

data %>%
  group_by(ID) %>%
  summarize(
    conditionA = max(conditionA), 
    conditionB = max(conditionB),
    conditionC = max(conditionC)
  )

The group_by() will group by ID , then the summarize() fnction will coalesce all rows under that ID to a single one. group_by()将按ID分组,然后summarize()函数将将该ID下的所有行合并为一个。 conditionA will assume the maximum value found in all rows for that ID, that is, if a 1 is present, then it will be one; conditionA将假定在该 ID 的所有行中找到的最大值,即,如果存在 1,则它将为 1; if only 0s are present, then the maximum will be zero.如果仅存在 0,则最大值为零。 Same for conditionB , and conditionC . conditionBconditionC相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何仅保留特定值与R中的另一列唯一关联的列 - How to retain only columns where a specific value is associated uniquely with another column in R R编程:分配一列,但仅在另一列中使用特定值 - R programming: Assign a columns but only with specific values in another column 使用R,如何根据一列以及要选择的列名称从不同的列中选择值? - Using R, how to select values from different columns depending on one column with the name of the column to select? 将具有 X 个唯一值的列解析为 X 个新列,并填充来自另一列 R 的值 - Parse a column with X unique values into X new columns, populated with values from another column R 如何在匹配R中的其他列时将特定值从一个数据列复制到另一个数据列? - How to copy specific values from one data column to another while matching other columns in R? 选择R中某些列的唯一组合,并为另一列选择随机值 - select unique combinations of some columns in R, and random value for another column 如何在与R中另一列中的重复项相关联的列中对值进行求和? - How to sum values in a column associated with duplicates in another column in R? 仅选择数据框中与R中另一个数据框具有相同列名的列 - Select only the columns in a dataframe which have the same column names as another dataframe in R 根据 R 中另一列中的值范围按列值选择行 - Select rows by column value based on range of values in another column in R 在其他列中填充一系列可能值的列:R - Populate column which a range of possible values in other columns: in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM