我有以下数据框
glimpse(Sample)
Observations: 4
Variables: 5
$ Product <chr> "A", "B", "C", "D"
$ Revenues <dbl> 50, 25, 15, 10
$ Quantity <dbl> 40, 30, 20, 10
$ RevenueCum <dbl> 50, 75, 90, 100
$ QuantityCum <dbl> 40, 70, 90, 100
我想使用for循环逐行显示列的每一行。但是,我的代码在每次迭代中都打印了列的所有值。
length=nrow(Sample)
for (i in 1:length)
{print(i)
Sample %>%select(Revenues, Quantity) %>% print(Revenues[i-1]," ",Revenues[i]," ",Quantity[i-1]," ",Quantity[i])
print(i)
}
这是我得到的结果:
[1] 1
# A tibble: 4 x 2
Revenues Quantity
<dbl> <dbl>
1 50 40
2 25 30
3 15 20
4 10 10
[1] 1
[1] 2
# A tibble: 4 x 2
Revenues Quantity
<dbl> <dbl>
1 50 40
2 25 30
3 15 20
4 10 10
[1] 2
[1] 3
# A tibble: 4 x 2
Revenues Quantity
<dbl> <dbl>
1 50 40
2 25 30
3 15 20
4 10 10
[1] 3
[1] 4
# A tibble: 4 x 2
Revenues Quantity
<dbl> <dbl>
1 50 40
2 25 30
3 15 20
4 10 10
[1] 4
>
编辑: 我计划要做的是打印一个ggplot,以便我可以使用这些所需的Revenue和Quantity值在for循环的每次迭代中添加一个矩形。在每次迭代时,这些值都将用作矩形的四个坐标。
答案 0 :(得分:0)
听起来您可能正在朝这个方向前进。
library(tidyverse)
# Sample data
sample <- data.frame(
stringsAsFactors = F,
Product = c(LETTERS[1:4]),
Revenues = c(50, 25, 15, 10),
Quantity = c(40, 30, 20, 10)
) %>%
mutate(RevenueCum = cumsum(Revenues),
QuantityCum = cumsum(Quantity))
# Add prior totals and set as zero where not available
sample_shapes <- sample %>%
mutate(RevenueCum_prior = lag(RevenueCum, default = 0),
QuantityCum_prior = lag(QuantityCum, default = 0))
# Plot
ggplot(sample_shapes, aes(xmin = QuantityCum_prior, ymin = RevenueCum_prior,
xmax = QuantityCum, ymax = RevenueCum, fill = Product)) +
geom_rect() +
labs(x = "Cumulative Quantity",
y = "Cumulative Revenue")