【发布时间】:2013-12-31 06:48:38
【问题描述】:
我无法创建一个循环,我不知道出了什么问题。我的数据包含列表中的列表。我有 >50 个主要列表,即 [[i]]。每个 [[i]] 包含 20 个 `i` (=sublist)。我的数据子集看起来像
>data
[[1]]$`1`
X Y Height_m kt_Result
1 253641.0 2630050 90 560
74 253845.7 2630552 90 270
156 254353.6 2630195 130 0
171 254554.9 2630220 170 390
173 254565.9 2630323 120 304
[[1]]$`2`
X Y Height_m kt_Result
5 253641.0 2630050 50 860
77 253845.7 2630552 20 370
159 254353.6 2630195 190 20
177 254554.9 2630220 140 310
200 254565.9 2630323 100 804
... ...
[[2]]$`1`
X Y Height_m kt_Result
4 253641.0 2630050 10 960
78 253845.7 2630552 20 220
150 254353.6 2630195 330 5
377 254554.9 2630220 670 340
100 254565.9 2630323 220 314
... ...
当我想在一个图中用不同颜色绘制每个子列表时,它不起作用
#blank plot (dfs is a different data frame with the same data)
plot(dfs[[1]]$kt_Result, dfs[[1]]$Height_m, type='n')
#plot sublist
lapply(1:length(data[[1]]), function(i)
points(data[[1]]$`i`$kt_Result, data[[1]]$`i`$Height_m,
ylim=rev(c(0, max(data[[1]]$`i`$Height_m))),
xlim= c(min(data[[1]]$`i`$kt_Result, na.rm=TRUE),
max(data[[1]]$`i`$kt_Result, na.rm=TRUE)), lwd=2, type='b',col=i))
我收到没有任何情节的警告
There were 50 or more warnings (use warnings() to see the first 50)
> warnings()
Warning messages:
1: In max(data[[1]]$i$Height_m) : no non-missing arguments to max; returning -Inf
2: In min(data[[1]]$i$kt_Result, na.rm = TRUE) :
no non-missing arguments to min; returning Inf
3: In max(data[[1]]$i$kt_Result, na.rm = TRUE) :
no non-missing arguments to max; returning -Inf
... ...
当我在没有任何 x-/y- 限制的情况下进行绘图时,它不会给出警告或绘图,只是在工作区中显示 NULL!
lapply(1:length(data[[1]]), function(i)
points(data[[1]]$`i`$kt_Result, data[[1]]$`i`$Height_m,
lwd=2, type='p',col=i))
[[1]]
NULL
[[2]]
NULL
...
[[20]]
NULL
但是,当我将数据逐个绘制时,它可以工作,但这是处理如此大的数据集的一种不切实际的方法
plot(dfs[[1]]$kt_Result, dfs[[1]]$Height_m, type='n')
points(data[[1]]$`1`$kt_Result, data[[1]]$`1`$Height_m, col='red')
points(data[[1]]$`2`$kt_Result, data[[1]]$`2`$Height_m, col='green')
... ...
points(data[[1]]$`19`$kt_Result, data[[1]]$`19`$Height_m, col='cyan')
points(data[[1]]$`20`$kt_Result, data[[1]]$`20`$Height_m, col='blue')
知道为什么这个简单的循环不起作用吗?
【问题讨论】:
-
这可能是少数几个地方之一,
for循环在 R 中是有意义的,我会尝试的。 -
您期望某些东西可以通过设计工作而不会起作用。
$从不 评估它的论点。 See this answer 了解更多信息并使用[,i]而不是$。 -
reshape2::melt(data)会将您的数据转换为非常适合 ggplot2 或 lattice 的长格式 data.frame。 -
用 R 基础解决此类问题的任何方法?
-
@baptiste,好主意,没有意识到
melt可用于嵌套列表。不过,您确实需要这样做:melt(data, id.vars=c("height", "weight"))。我将在下面更新我的代码。
标签: r list loops lapply sublist