
[英]Error “Attribute not identical” in using gather function for the multi column in R
[英]What R function can I use to check if the values of a column are identical based on an attribute?
如果您的解决方案可以包含基于 tidyverse package 的解决方案,那就太好了。
基本上,我试图按标题为“属性”的列进行分组,并测试“值”列中的所有值是否相同。
这是我的预期结果:
如您所见 - 对于 Mustang,Value 列全为 1。因此我们将匹配项设置为 =“Yes”。
对于 Corvette 和 Charger,由于其中一个值关闭,我们将 Matches 设置为 =“No”
我试过了:
数据 <- group_by(Attribute) %>% mutate(Matches = ifelse(first(value),= any(Value), "Yes", "No")
没用。 任何帮助深表感谢!
any(Value)
并没有真正做我们想要的,因为any
根据它是否有任何大于 0 的值返回 TRUE/FALSE。 此外还有一些拼写错误( data <- group_by(Attribute)
- 它应该是data %>% group_by(Attribute)
)
> any(c(1, 0, 5))
[1] TRUE
> any(c(0, 0, 0))
[1] FALSE
我们可能需要检查不同元素的数量( n_distinct
)是否等于 1
library(dplyr)
data <- data %>%
group_by(Attribute) %>%
mutate(Matches = c("No", "Yes")[1 + (n_distinct(Value) == 1)])
# // or using ifelse
# mutate(Matches = ifelse(n_distinct(Value) == 1, "Yes", "No"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.