绘制表格不同列中某一行的值

时间:2012-11-13 08:43:46

标签: r

我有一张巨大的桌子,我想在这张桌子上写下两个不同的行。

下面您可以看到我的数据集的小概述。

我想现在为国家4制作1,2和3年的制作,以便有人可以看到随时间的变化

与国家6相同

在X轴上应该是年份,在Y轴上应该是值。

有人能帮助我吗?

提前致谢!

   country    year1        unit        year2        unit    year3
    1          5.1         tonnes       1.4         tonnes   5
    2          4.9         tonnes       1.4         tonnes   2
    3          4.7         tonnes       1.3         tonnes   3.5
    4          4.6         tonnes       1.5         tonnes   8
    5          5.0         tonnes       1.4         tonnes   8
    6          5.4         tonnes       1.7         tonnes   6

1 个答案:

答案 0 :(得分:3)

这些是创建情节的步骤。

数据:

dat <- read.table(text="country    year1      unit      year2      unit    year3
   1          5.1         tonnes       1.4         tonnes   5
   2          4.9         tonnes       1.4         tonnes   2
   3          4.7         tonnes       1.3         tonnes   3.5
   4          4.6         tonnes       1.5         tonnes   8
   5          5.0         tonnes       1.4         tonnes   8
   6          5.4         tonnes       1.7         tonnes   6", header = TRUE)
  1. 选择数据的子集:

    subdat <- dat[dat$country == 4, c("year1", "year2", "year3")]
    
  2. 以长格式排列数据:

    subdat_l <- data.frame(Value = unlist(subdat), Year = factor(1:3))
    
  3. 简介:

    plot(Value ~ Year, subdat_l)
    
  4. enter image description here


    如果实际数据框由超过三年的数据组成,您可以使用这种通用方法:

    years <- grep("^year", names(dat), value = TRUE) # find the columns with the data
    subdat <- dat[dat$country == 4, years]
    subdat_l <- data.frame(Value = unlist(subdat),
                           Year = substr(years, 5, nchar(years)))