In tidyr, what criteria does the function `gather` use to map a dataframe from wide to long?

↘锁芯ラ 提交于 2019-12-03 15:51:09

In "tidyr", you specify the measure variables for gather in the ... argument. This is a little bit different conceptually from melt, where many examples (even many answers here on SO) would show the use of the id.vars argument (with the assumption that anything that is not specified as an ID is a measurement).

The ... argument can also take a - column name, as in the example you have shown. This basically says to "gather all of the columns except for this one". Another shorthand approach in gather includes specifying a range of columns by using the colon, for example, gather(stocks, stock, price, X:Z).

You can compare gather with melt by looking at the code for the function. Here are the first few lines:

> tidyr:::gather_.data.frame
function (data, key_col, value_col, gather_cols, na.rm = FALSE, 
    convert = FALSE) 
{
    data2 <- reshape2::melt(data, measure.vars = gather_cols, 
        variable.name = key_col, value.name = value_col, na.rm = na.rm)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!