【发布时间】:2018-07-24 17:27:39
【问题描述】:
我想通过 tidyr/dplyr 函数使用查找表来添加包含其他数据的列。我找到了一些执行此操作的基本示例,但无法使其与我的数据一起使用,而且我并不真正了解这些功能,因为响应没有解释正在发生的事情。
我要匹配这个数据框中的id列:
>df
id sample_name fpkm conf_hi conf_lo quant_status
1 XLOC_000118 T1 33.857900 62.323300 5.3925000 OK
2 XLOC_000118 T2 169.793000 395.783000 0.0000000 OK
3 XLOC_000118 T3 41.869200 69.395700 14.3427000 OK
4 XLOC_009095 T1 1.472500 3.076350 0.0000000 OK
5 XLOC_009095 T2 3.828400 8.171850 0.0000000 OK
6 XLOC_009095 T3 1.806010 4.055220 0.0000000 OK
...添加到此查找表中的相同值,并将name 值添加到df 中lookupTable$name 匹配df$id 的新列中:
>lookupTable
id name
1 XLOC_000118 Xy13
2 XLOC_009104 Xy3
3 XLOC_009105 Zy3
4 XLOC_009095 Xy6
5 XLOC_018501 Xy9
6 XLOC_020049 Xy35
我尝试修改来自this question 的代码,但收到错误:
df %>%
gather(key = "col") %>%
left_join(ObLookup, by = "id") %>%
spread(key = id, value = name)
Error: `by` can't contain join column `id` which is missing from LHS
In addition: Warning message:
attributes are not identical across measure variables;
they will be dropped
我自己想出了以下解决方案,它产生了我想要的结果,但我想知道是否有使用 tidyr 或 dplyr 的解决方案:
> df$names <- lookupTable$name[match(df$id, lookupTable$id)]
> df
id sample_name fpkm conf_hi conf_lo quant_status names
1 XLOC_000118 T1 33.857900 62.323300 5.3925000 OK Obp13
2 XLOC_000118 T2 169.793000 395.783000 0.0000000 OK Obp13
3 XLOC_000118 T3 41.869200 69.395700 14.3427000 OK Obp13
4 XLOC_009095 T1 1.472500 3.076350 0.0000000 OK Obp6
5 XLOC_009095 T2 3.828400 8.171850 0.0000000 OK Obp6
6 XLOC_009095 T3 1.806010 4.055220 0.0000000 OK Obp6
【问题讨论】:
-
ObComplete数据集是什么 -
df,修改了代码
-
你需要
df %>% gather(key, val, -id) %>% left_join(lookupTable) %>% group_by(id) %>% mutate(rn = row_number()) %>% spread(id, name) -
既然您现在已经成为高级 Stack Overflow 提问者,请考虑提供您的示例数据,而不是通过发布
dput(df)的输出而不是复制粘贴。这使我们更容易为您提供帮助。如需有关此主题的帮助,您可能需要阅读:stackoverflow.com/questions/5963269/…Cheers! -
Akrun,该代码添加了名称,但将 id 值作为列传播,并在没有对应值的地方引入了一堆 NA。我想要“df”的原始结构,其中“name”包含在“id”匹配的列中。