根据行值添加特定的列值

时间:2019-12-03 17:48:27

标签: r mutate

我有一个数据框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对应于Rice,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,但是不知道如何为我的代码进行修改。

任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:1)

使用@page "/BigDataStateHasChanged" <h3>BigDataStateHasChanged</h3> <button class="btn btn-primary" @onclick="GenerateBigData">Generate big data</button> <button class="btn btn-primary" @onclick="ChangeOneRow">Change 1 row</button> @if(list != null) { @foreach(var item in list) { <li>@item</li> } } @code { List<int> list; const int cMaxNumbers = 10000; protected void GenerateBigData() { list = new List<int>(cMaxNumbers); for(int i = 0; i < cMaxNumbers; i++) { list.Add(i); } } protected void ChangeOneRow() { list[0] = 123456; StateHasChanged(); } } ,您可以执行以下操作:

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))