请考虑以下最小的工作示例:
library(magrittr) # for the %>% pipe
library(data.table)
# test data.table contains common_column and two others
test_dt <- data.table(test_column_one = c(1, 2, 3), test_column_two = c("x","y","z"), common_column = c("ID1", "ID2", "ID3") )
# some other data.table that contains common_column
other_dt <- data.table( additional_info = c("US", "US", "GB"), common_column = c("ID1", "ID2", "ID3"))
example_function <- function(dt_column){
# does some things on the data tables based on the column parameter passed
merged_dt <- merge(other_dt, test_dt[,.(common_column, dt_column)], by = "common_column") %>%
.[order(dt_column),] # order by the dt_column
return(merged_dt)
}
# calling the example function
example_function(test_dt$test_column_one)
如何将代码修改为:
- 相反,可以使用列名指定字符串作为参数
- 能够传递带有列名的向量或字符串列表
我希望尽可能避免for循环,并利用优化的data.table语法.
我try 使用特定于data.table的unlist()
和..
语法,但不知何故总是收到奇怪的错误消息,并且不确定如何继续.