I have a following sample data frame:
x<-c(1:4)
y<-c(9:12)
z<-c("a","b","c","d")
data<-data.frame(x,y,z) # as data:
x y z
1 1 9 a
2 2 10 b
3 3 11 c
4 4 12 d
I want to extract the column 2 or 3 using the function (note: I am using column names to extract). My code is as follows:
data_frame<-function(col){
cols<-c("y","z")
# column x is already there; it is not in a vector of col.
if (col %in% cols){
kk<-data[,c("x","col")]
return (kk)}
}
Now, I want the output for data_frame("y"). However, R gives me the following error:
data_frame("y")
Error in `[.data.frame`(data, , c("x", "col")) :
undefined columns selected.
I was wondering why R is not taking my argument col which is y here. I am a bit upset why R is interpreting argument col as the name of the column. Your valuable suggestion in this regard would be highly appreciated.
This part:
kk<-data[,c("x","col")]should bekk<-data[,c("x",col)]