尝试从数据表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谢谢你们的帮助。
发布于 2018-03-20 12:23:19
我相信以下措施会奏效:
x[tmp[, .(CountryName, Year)], pop - .SD, .SDcols = tmp$use.to.adjust]发布于 2018-03-20 11:58:36
如果我正确理解,您希望筛选您的data.table以选择条目,即'Lithuania'作为国家,2000作为年份。您所要求的减法的解决方案可能如下所示。
> my_filter <- x$CountryName == 'Lithuania' & x$Year == 2000
> x[my_filter]$pop - x[my_filter]$under1
[1] 3412https://stackoverflow.com/questions/49381238
复制相似问题