数据表在数据表中减去

时间:2018-03-20 10:02:58

标签: r data.table

尝试从数据表x中选择一个值并在数据表x中进行减法。 例如:

x <- data.table(CountryName = c("Lithuania", "Lithuania", "Latvia", "Latvia", "Estonia", "Estonia"),
            Year = c(2000, 2001, 2000, 2001, 2000, 2001),
            pop = c(3512, 3486, 2381, 2353, 1401, 1392),
            under1 = c(100, 150, 95, 98, 75, 65), 
            under2 = c(95, 135, 85, 89, 71, 62))
tmp <- data.table(CountryName = "Lithuania", Year = 2000, use.to.adjust = "under1")
setkey(x, CountryName, Year)

我正在尝试使用 tmp 表来确定哪些列用于减法并返回单个数值。

我的解决方案都没有工作。此外,我不想创建其他值,保存它们然后减去。 我的尝试:

x[tmp[, .(CountryName, Year)], pop - tmp$use.to.adjust, with = F ]
Error in eval(jsub, parent.frame(), parent.frame()) : 
 object 'pop' not found

x[tmp[, .(CountryName, Year)], pop - tmp$use.to.adjust ]
Error in pop - tmp$use.to.adjust : 
 non-numeric argument to binary operator

x[tmp[, .(CountryName, Year)], "pop" - tmp$use.to.adjust, with = F ]
 CountryName Year under1 under2
1:   Lithuania 2000    100     9

最后一个示例只是从数据表中删除pop列。

想得到:

value <- 3512 - 100

谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望过滤data.table以选择'Lithuania'作为国家/地区和2000作为年份的条目。你问的减法解决方案可能如下:

> my_filter <- x$CountryName == 'Lithuania' & x$Year == 2000
> x[my_filter]$pop - x[my_filter]$under1 
[1] 3412

答案 1 :(得分:0)

我相信以下内容可行:

x[tmp[, .(CountryName, Year)], pop - .SD, .SDcols = tmp$use.to.adjust]
相关问题