Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (50.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 (107k 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.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...