0 votes
1 view
in R Programming by (43.2k points)

With the help of the following code I want to define an empty dataframe which is having 5 number of columns and then as you can see with the help of for loop I am assigning values to each and every column.

k = 1:5

dfk = data.frame(k1 = c(), k2 = c(), k3 = c(), k4 = c(), k5 = c())

for (j in 1:5){

    for (i in 1:12){

        dfk[j] = c(dfk[j], i+j)

    }

    plot(1:12, dfk[j])

}

I am getting the following error:

"Error in [.data.frame(dfk, j): undefined columns selected Traceback: 1. dfk[j] 2. [.data.frame(dfk, j) 3. stop("undefined columns selected")"

1 Answer

0 votes
by (92.8k points)

Your way of performing that is correct but you have used too many c(). Kindly refer to the following code that will help you in achieving that output:

dfk = data.frame(matrix(ncol = 5, nrow = 0))

colnames(dfk) <- c("k1","k2","k3","k4","k5")

for (j in 1:5){

  for (i in 1:12){

    dfk[i,j] = i+j

  }

  plot(1:12, dfk[,j])

}

If you are a beginner and want to know more about R then do refer to the R programming tutorial that will you in a better way.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...