【问题标题】:Adding specific column value according to row value根据行值添加特定列值
【发布时间】:2020-03-28 11:18:20
【问题描述】:

我有一个数据框 h3

Genotype Preference
Rice     1
Rice     2
Lr       3
Lr       3
th       4
th       7

我希望数据框看起来像

Genotype Preference Haplotype
Rice     1          1
Rice     2          1
Lr       3          2
Lr       3          2
th       4          0.5
th       7          0.5

也就是说,我想添加一个数字变量,以添加到每种基因型中。对于每种基因型,我有大约 100 个观察值。我希望能够在一行代码中将数字变量添加到新列中,并确保添加 1 对应于大米,2 对应于 Lr,0.5 对应于 th。

我尝试用mutate/ifelse构造代码:

h3 %>% select(Genotype) %>% mutate(Type = ifelse (Genotype = c("Rice"), 1, Genotype))

我查找的其他结果提供了添加列的解决方案,该列具有从前列计算的值但不是特定值。

我找到了 dplyr mutate with conditional valuesApply R-function to rows depending on value in other column 但不知道如何为我的代码修改它。

对此的任何帮助将不胜感激。

【问题讨论】:

  • = 用于赋值,== 用于测试相等性。您尝试在 ifelse 内分配,而不是测试相等性
  • 谢谢@camille 那么我现在该如何构建我的代码呢?因为如果我使用 == 那么我得到的结果只包含我的基因型。我对 r 很陌生。
  • 不确定你的意思。但是ifelse(Genotype = c("Rice"), 1, Genotype))应该是ifelse(Genotype == "Rice", 1, Genotype)),如果你想要用1替换“Rice”

标签: r dplyr


【解决方案1】:

使用dplyr,您可以:

library(dplyr)
df %>% mutate(Haplotype = ifelse(Genotype == "Rice",1,ifelse(Genotype == "Lr",2,0.5)))

使用base,你可以做同样的事情:

df$Haplotype = ifelse(df$Genotype == "Rice",1,ifelse(df$Genotype == "Lr",2,0.5))

数据

df = data.frame("Genotype" = c("Rice","Rice","Lr","Lr","Th","Th"),
                "Preference" = c(1,2,3,3,4,7))  

【讨论】:

  • @KeerthiKrutha,很高兴它对你有用。仅供参考,ifelse 结构是第一个参数是要测试的条件,如果第一个参数为 True,则第二个参数是输出,如果第一个参数为 False,则第三个参数是输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多