2017-04-07 86 views
1

我有一个数据表,列名称为字符串。数据表列参考

虽然

datatable[RowNumber, `Column Name`] 

工作正常,

datatable[RowNumber,datatable2[RowNumber,,ColumnName]] 

不工作。

datatable2[RowNumber,,ColumnName2]= Column Name2 

我该如何解决这个问题?

+3

Erhm ...不明确,请提供[重现的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great- r-reproducible-example) – digEmAll

+0

你在说DT包还是'data.table'? – akrun

+0

你能改说你吗? – tagoma

回答

1

如果您将列名称作为文本字符串引用,而不是如此,那么您可能会遇到需要设置“with = FALSE”的问题。

library(data.table) 

head(iris) 

> head(iris) 
    Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
1   5.1   3.5   1.4   0.2 setosa 
2   4.9   3.0   1.4   0.2 setosa 

# its a data.frame so convert to data.table 
dt <- as.data.table(iris) 

dt[1, Sepal.Length] 
# get 5.1  

dt[1, "Sepal.Length"] 
# gives error, so you need with! 

dt[1, "Sepal.Length", with = FALSE] 
# get 5.1 

# usually this is done when you code columns programmatically 
my.col <- "Sepal.Length" 
dt[1, my.col, with = FALSE] 
# get 5.1