如何正确处理函数中的协变量,其名称列在字符串中?

时间:2018-03-09 21:33:56

标签: r nse

我有一长串协变量列表,我希望将其存储为字符串,以便在多个函数中更方便地使用它。

我认为该问题与this question有关,但我不能将其应用于与回归公式不同的案例。

userOnlineView.setVisibility(View.INVISIBLE);

或其他案例

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AsyncSubject } from 'rxjs/AsyncSubject';

import 'rxjs/add/operator/do';
import 'rxjs/add/observable/of';


class CachedResponseObject {
    asyncSubject: AsyncSubject<HttpEvent<any>>
    timeStamp: Date = new Date()
}

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
    private cache: { [name: string]: CachedResponseObject } = {};

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (request.method !== 'GET') {
            this.cache = {}; // Empty cache after POST or DELETE
            return next.handle(request);
        }

        // Delete all get-requests older than 5 seconds
        for (const key in this.cache) {

            if (this.cache[key].asyncSubject) {

                const currentTimeStamp: Date = new Date();

                const diff = (currentTimeStamp.getTime() - this.cache[key].timeStamp.getTime()) / 1000;

                if (diff > 5) {
                    delete (this.cache[key])
                }
            }

        }

        const cachedResponse = this.cache[request.urlWithParams] || null;

        if (cachedResponse) {
            return cachedResponse.asyncSubject// .delay(0);
        }

        const subject = this.cache[request.urlWithParams] = new CachedResponseObject()
        this.cache[request.urlWithParams].asyncSubject = new AsyncSubject<HttpEvent<any>>();
        this.cache[request.urlWithParams].timeStamp = new Date()

        next.handle(request).do(event => {
            if (event instanceof HttpResponse) {
                subject.asyncSubject.next(event);
                subject.asyncSubject.complete();
            }
        }).subscribe(); // must subscribe to actually kick off request!
        return subject.asyncSubject;
    }
}

特别是粘贴版我不明白它为什么不起作用,虽然它产生与括号中的字符串完全相同的字符串:

xvar <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")

with(iris, iris[order(Sepal.Length, Sepal.Width, 
                      Petal.Length, Petal.Width), ])  # working

with(iris, iris[order(xvar), ])  # not working

我错过了什么?

1 个答案:

答案 0 :(得分:1)

重要的是要注意字符值和实际代码是非常不同的。只需比较

 with(iris, order("Sepal.Length"))
 with(iris, order(Sepal.Length))

paste()这样的函数只生成字符串而noquote()也只返回字符串,它只是不打印引号。如果您尝试动态创建代码,通常需要将字符串解析为正确的R语言对象。有时你可以做一些偷偷摸摸的选择。

一种可能的解决方法是使用do.call将要排序的列作为单独的参数传递给order。你可以做到

iris[do.call("order", iris[xvar]), ]

dplyr包有tidyevels方法也可以帮助解决问题

library(dplyr)
iris %>% arrange(!!!rlang::syms(xvar))