Home > Enterprise >  R syntax explanation needed
R syntax explanation needed

Time:07-22

R beginner: trying to understand code within a for loop to adapt to my own dataset

--> Can someone please explain what the syntax "5" does/means in the last line of this code part of a for-loop head:

vd_ID <- c(unique(vd$Respondent))

id <- (vd_ID[i])

x <- c(1:length(as.numeric(vd[vd$Respondent == id, 5])))

Thanks!

CodePudding user response:

The 5 is a column index. In this case, it is specifying that you want to return the fifth column of object vd. More precisely, it is specifying that you want the fifth element of the vector of columns for object $vd$.

When working with a data.frame like I suspect vd to be, you can extract rows and columns using vd[rows,columns] where you can replace rows with a number or vector of numbers to specify the row(s) to get and replace columns with a number or vector of numbers to specify the column(s) to get. If you omit rows or columns, R assumes you want all of the rows or columns. For example vd[3, ] is all row 3 for all columns while vd[ ,2] is column 2 for all rows.

  • Related