【发布时间】: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 values 和 Apply 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”