使用data.table列中的参数通过引用更新

时间:2017-06-23 18:24:49

标签: r data.table

我有以下数据表和函数,它提取参数并将其作为列添加到数据表中:

library(stringr)
library(data.table)

pq <- c("cm_mmc=MSN-_-Exact-_-BrandExact-_-CheddarCheese"
  ,"cm_mmc=Google-_-cheeseTypes-_-cheddar-_-cheesedelivered&gclid=CMXyy2D81MsCFcsW0w0dMVoPGw"
  ,"cm_mmc=MSN-_-worldcitiesuslocations-_-cheese-_-cheeseshops"
  ,"cm_mmc=MSN-_-worldcitiesuslocations-_-cheese-_-cheeseshops")


rq <- c("q=cheese&src=IE-SearchBox&FORM=IESR02",
                   "sa=L",
                   "q=london+cheese+shop&src=IE-TopResult&FORM=IETR02&pc=WCUG",
                   "q=london+cheese+shop&src=IE-TopResult&FORM=IETR02&pc=WCUG")

DT = data.table(page_urlquery = pq, refr_urlquery = rq)

# Extracts a paramater from the relevant query and adds it to the table as a column
extract_param <- function(dt, source = c("page_urlquery", "refr_urlquery"), param_name){
  source <- match.arg(source)
  regexp <- paste("(?i)", param_name, "=([^&]+)", sep="")
  col_name <- switch(source
                     ,"page_urlquery" = paste("url_", param_name, sep = "")
                     ,"refr_urlquery" = paste("ref_", param_name, sep = "")
  )

  dt[,(col_name):= str_match((source), regexp)[,2]]
}

然而,当我按如下方式调用该函数时:

extract_param(DT, "page_urlquery", "cm_mmc")

它会创建列,但内容为空。我认为数据表(source)参数中的语法有问题。我错过了什么?

1 个答案:

答案 0 :(得分:1)

更改函数内的代码

public class TestDemo extends JPanel implements ActionListener {
  private static final long serialVersionUID = 1L;
  private int x;
  private int y;
  Timer timer;

TestDemo() {
    x = 0;
    y = 0;
    this.setBackground(Color.BLACK);
    timer = new Timer(10, this);
    timer.start();
}

public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.scale(1, 1);
    g2d.setPaint(Color.RED);
    g2d.fill(new Rectangle2D.Double(getX(), getY(), 20, 20));
}

public void actionPerformed(ActionEvent e) {
    setX(getX() + 1);
    repaint();
}

public static void main(String[] args) {
    JFrame frame = new JFrame("Moving star");
    JPanel testDemo = new TestDemo();
    testDemo.setSize(800, 200);
    frame.add(testDemo);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}
public int getY() {
    return y;
}
public void setY(int y) {
    this.y = y;
}
}

dt[,(col_name):= str_match((source), regexp)[,2]]