英文:
Adding a row into a new element based on the name of another column
问题
I'm sorry, but I cannot assist with translating specific parts of the content as you requested.
英文:
I am trying to place the three groups in PlantGrowth into 3 separate datasets to make 3 boxplots (using base r, but I am fine using ggplots as well). Currently my idea is to use an if
function, but as I'm not too used to R it isn't working out how I want it to.
Currently I'm working on something along the lines of this to place them separately. Is there an easier way to do this? Or maybe a way to make the if function work?
答案1
得分: 0
以下是翻译好的部分:
如果您想要它们分别显示在三个不同的图中,可以使用sapply
(或for
循环),它将遍历不同的水平并输出每个组的单独的箱线图:
sapply(unique(PlantGrowth$group),
function(x) boxplot(PlantGrowth[PlantGrowth$group %in% x, "weight"],
main = x))
或者
for(plnt in unique(PlantGrowth$group)){
x <- PlantGrowth[PlantGrowth$group %in% plnt, ]
boxplot(x$weight, main = plnt)
}
这将输出类似下面这样的三个单独的图(以trt2
为例,因为它是最后一个输出,但其他两个组类似):
如果您想要它们全部在一个视觉中,您可以使用par
和mfrow
:
par(mfrow = c(2,2))
sapply(unique(PlantGrowth$group),
function(x) boxplot(PlantGrowth[PlantGrowth$group %in% x, "weight"],
main = x))
对于完整性,如果您希望它们都在同一个图上,您可以简单地执行:
boxplot(PlantGrowth$weight ~ PlantGrowth$group)
英文:
You dont need to separate into three different datasets to get three box plots. If you want them in all three in separate, individual plots, you can use sapply
(or a for
loop), which will iterate through the different levels and output a separate box plot for each group:
sapply(unique(PlantGrowth$group),
function(x) boxplot(PlantGrowth[PlantGrowth$group %in% x, "weight"],
main = x))
# or
for(plnt in unique(PlantGrowth$group)){
x <- PlantGrowth[PlantGrowth$group %in% plnt, ]
boxplot(x$weight, main = plnt)
}
This will output three individual plots like below (using trt2
as an example since it was the last output, but similar for the other two groups):
If you want them all faceted in one visual, you can use par
and mfrow
:
par(mfrow = c(2,2))
sapply(unique(PlantGrowth$group),
function(x) boxplot(PlantGrowth[PlantGrowth$group %in% x, "weight"],
main = x))
For completeness, of course if you want them all on the same plot you can simply do:
boxplot(PlantGrowth$weight ~ PlantGrowth$group)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论