r-如果其他人在里面观察闪亮-不等待触发



在代码的某些部分,我有以下观察对象。在我添加if语句之前,它运行良好。当脚本运行时,语句立即执行,并且不等待触发与观察相关的操作。如果在里面观察,我该怎么做才能"稳住阵脚"呢?

observe({
print("UPDATING COORDS")
print(input$map_marker_dragend)
id <- input$map_marker_dragend$id
lat_nova <- input$map_marker_dragend$lat
lon_nova <- input$map_marker_dragend$lng
print(lat_nova)
print(lon_nova)
print(WP$df$latitude)
df2 <- ifelse(is.null(df2), WP$df, df2) # this is the line causing problem
df2 <- if (is.null(df2)) return(WP$df) else return(df2) # this is a second try to make it work
df2$latitude[which(WP$df$id == id)] <- lat_nova
df2$longitude[which(WP$df$id == id)] <- lon_nova
print(df2$latitude)
print(df2, width = Inf)
# declaring to later use
WP$df2 = df2
})

基本上,我想要的是闪亮的检查df2是否存在。。。如果不超过df2应该是WP$df。。。如果是,则df2=df2并继续计算。

谢谢!

ifelse被矢量化,返回值的长度取决于条件(第一个参数(的长度。我推断你的df2WP$df2data.frames,这意味着如果is.null(df2)的长度是1,那么WP$df的"长度"不是,它实际上与ncol(WP$df)相同。这可以在这里看到:

length(mtcars)
# [1] 11
ncol(mtcars)
# [1] 11
nrow(mtcars)
# [1] 32
ifelse(TRUE, mtcars, iris)
# [[1]]
#  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 10.4 14.7 32.4
# [19] 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4

这是mtcars的第一列(作为list(。(知道data.frame实际上只是一个list,其中每个元素的长度都相同,这可能会有所帮助。在传统的方式中,每个元素都是vector,但也可以有更复杂的对象("列表列"(。(

通常假设test=yes=no=自变量到ifelse的长度要么都是相同的长度,要么是长度为1(这允许循环使用(。但这既没有经过测试,也没有强制执行:

ifelse(TRUE, 1:2, 11:13)
# [1] 1
ifelse(c(FALSE, TRUE), 1, 11:13)
# [1] 11  1ifelse(c(FALSE, TRUE, FALSE), 1, 11:12)
# [1] 11  1 11

由此可以推断,这些对象被回收的数量与填充到test=长度所需的数量一样多。

因此,在您的情况下,ifelse(is.null(df), WP$df, df2)只返回其中一列的第一列。

关于您的代码的其他内容:不要使用return

我建议你的代码应该是

observe({
print("UPDATING COORDS")
print(input$map_marker_dragend)
id <- input$map_marker_dragend$id
lat_nova <- input$map_marker_dragend$lat
lon_nova <- input$map_marker_dragend$lng
print(lat_nova)
print(lon_nova)
print(WP$df$latitude)
if (is.null(df2)) df2 <- WP$df
df2$latitude[which(WP$df$id == id)] <- lat_nova
df2$longitude[which(WP$df$id == id)] <- lon_nova
print(df2$latitude)
print(df2, width = Inf)
# declaring to later use
WP$df2 = df2
})

(我假设WP来自reactiveValues,否则最后一行的分配将不会保存。(

最新更新