我有两个数据框:
farm_production <- data.frame (
year = c(seq(1980,2000)),
"n11" = c(seq(80,200,length.out=21)),
"n26" = c(seq(110,180,length.out=21)),
"n31" = c(seq(150,56,length.out=21)),
"n48" = c(seq(200,160,length.out=21)),
"n59" = c(seq(198,170,length.out=21)))
farm_info <- data.frame (
ID = c("n11", "n26", "n31", "n48", "n59"),
type = c("wheat", "wheat", "cereal", "hay", "hay"),
country = c("Spain", "Greece", "Italy", "Spain", "Portugal"))
这两个数据帧在具有相同值的公共单元格中(n11,n26,n31,n48,n59)
我绘制了这5个农场历年的产量:
plot(farm_production$year, farm_production$n11, xlab = "Year", ylab = "Forage production (tons)", ylim = c(0, 200))
points(farm_production$year, farm_production$n26)
points(farm_production$year, farm_production$n31)
points(farm_production$year, farm_production$n48)
points(farm_production$year, farm_production$n59)
但是,我想按“类型”对这些点进行着色(3 个级别:小麦、谷物、干草),但此信息位于“farm_info”数据框中,如何将一个数据框的信息与另一个数据框关联起来?
我知道我可能可以手动执行此操作,但请记住,这只是一个具有 100 多行和列的更大数据帧的小样本,所以 我有兴趣找到一种“自动化”的方法此过程通过将数据帧 1 (farm_product) 中的信息与数据帧 2 (farm_info) 相关联,以按“类型”对这些点进行着色。
对我如何做到这一点有什么建议吗?非常感谢任何帮助。
farm_production <- data.frame (
year = c(seq(1980,2000)),
"n11" = c(seq(80,200,length.out=21)),
"n26" = c(seq(110,180,length.out=21)),
"n31" = c(seq(150,56,length.out=21)),
"n48" = c(seq(200,160,length.out=21)),
"n59" = c(seq(198,170,length.out=21)))
farm_info <- data.frame (
ID = c("n11", "n26", "n31", "n48", "n59"),
type = c("wheat", "wheat", "cereal", "hay", "hay"),
country = c("Spain", "Greece", "Italy", "Spain", "Portugal"))
data <- tidyr::pivot_longer(
farm_production,
-year,
names_to = "farm",
values_to = "production"
) |>
dplyr::left_join(
farm_info,
dplyr::join_by(farm == ID)
) |>
dplyr::mutate(
type = factor(type)
)
plot(
data$year,
data$production,
xlab = "Year",
ylab = "Forage production (tons)",
ylim = c(0, 200),
col = data$type
)
legend(
x ="topleft",
legend = levels(data$type),
col = 1:3,
pch = 19,
cex = .7
)
创建于 2024-02-27,使用 reprex v2.1.0