【问题标题】:R dplyr mutate in a functionR dplyr 在函数中发生变异
【发布时间】:2018-05-08 04:32:03
【问题描述】:

这应该是一个非常直接的代码,我只是想将新变量绑定到现有数据帧。但是, dplyr mutate 似乎在函数中不起作用。当我调用函数 addLocation 时,没有添加项目。

位置数据 (df.russia_locations)

 location    lon         lat
 Kalingrad  20.45221    54.71043        
  Moscow    37.61730    55.75583    

绑定到 itemTest(可以是任何数据集)

     addLocation <- function(itemInfo){ itemInfo <- mutate(itemInfo,
                                     Kalingrad_lon = df.russia_locations[1,2],
                                     Kalingrad_lat = df.russia_locations[1,3],
                                     Moscow_lon = df.russia_locations[2,2],
                                     Moscow_lat = df.russia_locations[2,3]
                                    )}
     addLocation(itemTest)

我一定是错过了什么?

【问题讨论】:

  • @RonakShah 是位置数据帧

标签: r tidyr dplyr


【解决方案1】:

您需要在函数中的最后一个括号之前添加return(itemInfo),或删除函数中的itemInfo &lt;- 分配。如果将函数的输出分配给名称,则会得到预期的打印输出。

> itemTest2 <- addLocation(itemTest)
> length(addLocation(itemTest))
[1] 5
> length(addLocation(itemTest))==length(itemTest)
[1] FALSE

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2019-12-06
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多