R:使用for循环和过滤数据表 [英] R: Using for-loop and filter data.table
问题描述
我想循环遍历一个列表,用于子集data.table并通过几行代码运行结果。使用变量进行子操作在没有for循环的情况下工作正常,但是当循环包含时,它不能按预期工作。我想这个问题是由数据类型或范围引起的。
I'm trying to loop through a list which is used to subset a data.table and run the results through few lines of code. Subseting with a variable is working perfectly without the for loop but when the loop is included it does not work as expected. I guess the problem is either caused by data type or scope.
以下代码完美地工作:
dt <- data.table(mpg)
list <- levels(dt$manufacturer)
dt[manufacturer==list[3]]
如果我尝试使用for循环遍历列表:[updated code - 已解决]
If I then try to loop through the list with a for loop: [updated code - solved]
for (var in list) {
subs <- data.table(melt(dt[manufacturer==var, list(model, hwy, cty)], id.vars='model'))
png(paste(var, 'png', sep='.'))
print(ggplot(subs, aes(model, value, col=variable)) + geom_point())
dev.off()
}
我没有任何东西。
应该平等地工作。有没有人有一个建议,什么可能导致我没有得到任何东西与第二次过滤?
For me the code parts look identical and should work equally. Does anyone have a suggestion what might cause that I do not get anything with the second filtering ? Any help is appreciated.
推荐答案
这是一个很常见的问题。检查区别:
This is a very common question. Check the difference:
for (i in 1:5) {i}
# no output
for (i in 1:5) {print(i)}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
但是,代码执行:
for (i in 1:5) {j <- i^2}
j
[1] 25
只要使用全局变量来存储结果,如果你在循环中运行一些代码。
Just use a global variable to store results in if you are running some code in a loop.
UPD:
此讨论:
在循环中,自动打印关闭,因为它在函数内。如果您想要查看输出,您需要在这两种情况下显式打印。
In a loop, automatic printing is turned off, as it is inside a function. You need to explicitly print something in both cases if you want to see the output.
缺少打印只是一个约定,从偶尔垃圾邮件。
The absence of printing is just a convention, which is preventing your console from being occasionally spammed.
这篇关于R:使用for循环和过滤数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!