0

グループがあり、各人にスペース区切りのテキスト ファイルがあります。これらのファイルでは、右の値はその人の身長を示しcm、左の値は日付を次の%d/%m/%Y形式で示します。

09/05/1992 0
17/03/1993 50
02/08/1994 65.5
03/12/1995 72

の身長は0その人の生年月日を表します。

このRスクリプトは、ジョンとエイミーの身長のグラフを描画し、PDF に出力します。

pdf("Heights.pdf")

john <- read.table("John",sep="")
names(john) <- c("time","height")
jt <- strptime(john$time, "%d/%m/%Y")
jh <- john$height

amy <- read.table("Amy",sep="")
names(amy) <- c("time","height")
at <- strptime(amy$time, "%d/%m/%Y")
ah <- amy$height

plot(jt,jh,type="b",pch=20,col="red",
xlab="Date",ylab="Height",
ylim=c(min(jh,ah),max(jh,ah)))
points(at,ah,type="b",pch=20,col="green")
title("Heights")

このスクリプトを次のように拡張するにはどうすればよいですか:

  • 現在のディレクトリ内の末尾が.heights?のすべてのファイルをグラフ化します。
  • 各人の生年月日を基準にしてグラフを作成しますか?
4

1 に答える 1

2

これでいけると思います。ggplot でプロットするのが最も簡単な方法です。そこからプロットをきれいにすることができます。

# Get all the files ending with .heights
filelist <- list.files(pattern = "\\.heights")

# Get all the data. Put into a single data.frame
# Assuming that you don't have thousands of
# files/measurements, rbind()ing shouldn't be too slow. 
df <- data.frame(person = character(),
                 dates = character(),
                 height = numeric())

# Iterate through, collecting the data into a data.frame
for (fname in filelist){
  x <- read.table(fname, sep="", as.is = TRUE)
  person <- gsub("\\.heights", "", fname)
  names(x) <- c("dates", "height")
  df <- rbind(df, data.frame(person = rep(person, times = nrow(x)),
                             dates = x$dates, 
                             height = x$height))
}

# Convert dates to POSIXct
df$dates <- strptime(as.character(df$dates), "%d/%m/%Y")
df$dates <- as.POSIXct(df$dates)

# Plot with qplot
require(ggplot2)
pdf("Heights.pdf")
qplot(dates, height, data = df, color = person)
dev.off()

# Plot with base graphics
pdf("Heights_2.pdf")
plot(df$dates, df$height, col = as.numeric(df$person))
dev.off()
于 2010-08-02T00:36:49.287 に答える