Noob is here to R. Trying to understand something. I need to create a function that will add a new column to the beginning of the dataset. This new column is a concatenation of values in other columns that the user specifies.
Imagine this is a dataset called myDataSet:
col_1 col_2 col_3 col_4
bat red 1 a
cow orange 2 b
dog green 3 c
The user can use the following function:
addPrimaryKey(myDataSet, cols=c(1,3,4))
to get the result of a new dataset with columns 1, 3 and 4, combined into a column with the name ID and added to the beginning, for example:
ID col_1 col_2 col_3 col_4
bat1a bat red 1 a
cow2b cow orange 2 b
dog4c dog green 3 c
This is the script I was working on, but I looked at it for so long, I think I made some mistakes. I cannot figure out how to correctly get the column numbers from the arguments in the insert function.
addPrimaryKey <- function(df, cols=NULL){
newVector = rep(NA, length(cols))
colsN <- as.numeric(cols)
df <- cbind(ID=paste(
for(i in 1:length(colsN)){
holder <- df[colsN[i]]
holder
}
, sep=""), df)
df
}
Any help would be greatly appreciated. Many thanks