문제

R을 사용하여 데이터 프레임을 통해 루프를 사용하고 계산을 수행하고 플롯을 만듭니다.

for(i in 2 : 15){
# get data
dataframe[,i]  

# do analysis

# make plot
a <- plot()
}

'i'의 값을 사용하여 플롯 객체 이름 'a'를 만들 수있는 방법이 있습니까? 예를 들어, a + "i"<- plot (). 그런 다음 벡터에 추가하여 PDF를 만들고 싶을 때 이후 단계에서 사용할 수있는 일련의 플롯이 있습니다. 또는 이것을 저장하는 또 다른 방법이있을 수 있습니다.

나는 Paste () 함수에 익숙하지만 그것을 사용하여 물체를 정의하는 방법을 찾지 못했습니다.

도움이 되었습니까?

해결책

당신이 플롯 객체의 "벡터"를 원한다면, 가장 쉬운 방법은 아마도 그것들을 list. 사용 paste() 플롯의 이름을 만들고 목록에 추가하려면 다음과 같습니다.

# Create a list to hold the plot objects.
pltList <- list()

for( i in 2:15 ){

  # Get data, perform analysis, ect.

  # Create plot name.
  pltName <- paste( 'a', i, sep = '' )

  # Store a plot in the list using the name as an index.
  # Note that the plotting function used must return an *object*.
  # Functions from the `graphics` package, such as `plot`, do not return objects.
  pltList[[ pltName ]] <- some_plotting_function()

}

플롯을 목록에 저장하고 싶지 않고 문자 그대로 이름이 포함 된 새 개체를 만들고 싶었다면 pltName, 그러면 사용할 수 있습니다 assign():

# Use assign to create a new object in the Global Environment
# that gets it's name from the value of pltName and it's contents
# from the results of plot()
assign( pltName, plot(), envir = .GlobalEnv )

다른 팁

패키지를 살펴보십시오 lattice 또는 ggplot2,이 패키지의 플롯 함수는 변수에 할당 할 수 있으며 이후 단계에서 인쇄하거나 플롯 할 수있는 객체를 만듭니다.

예를 들어 lattice:

library("lattice")
i <- 1
assign(sprintf("a%d", i), xyplot(1:10 ~ 1:10))
print(a1) # you have to "print" or "plot" the objects explicitly

또는 개체를 목록에 추가하십시오.

p <- list()
p[[1]] <- xyplot(...)
p[[2]] <- xyplot(...)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top