1

I have a Current dataFrame like:

BaseTable
S.no.  Category    First  Second  Third
1      Abc Class    10     12      3
2      Xyz Class    12      3      4
3      asd Class    10      2      4

Now ,I want to add a column in this data frame using paste statement in data.frame. I have tried doing it with assign() and noquotes() but r create a new variable with that name.

First = unique(BaseTable$First)
Count = 1    
Combinations = c('First', 'Second', 'Third')
For(i in combinations){
   assign(paste("BaseTable$no", Count, "[BaseTable$", i ," %in% ", i[j], "]", sep = ''), j)
   Count = Count +1
}

The Output I am getting is a variable name BaseTable$no10[BaseTable$Perfect %in% Perfect] Secondly, here i is a vector which has multiple elements, but with paste statement, it show the i[j] values as NA. Like for First[1] = NA.

I want And output like:

BaseTable
S.no.  Category    First  Second  Third  No1   No2   No3
1      Abc Class    10     12      3      1     1     1
2      Xyz Class    12      3      4      2     2     2
3      asd Class    10      2      4      1     3     2
Karan
  • 115
  • 11
  • Please try to make a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so that it is easy for others to help you. – Ronak Shah Oct 22 '16 at 07:09
  • Could you illustrate how the desired `data.frame` should look? – Konrad Oct 22 '16 at 07:19
  • @Karan ? [duplicates] http://stackoverflow.com/questions/6112803/how-to-create-an-index-from-a-variable-in-a-dataframe – timat Oct 22 '16 at 08:15
  • @Karan, you should avoid the Capital letter.. and test your code before you post it the this one fo not work: `For` instead of `for`, `Combinations` instead of `combinations`. – timat Oct 22 '16 at 08:51
  • This is a sample code,in the real code there is no such problem, but from the next time i will be carefull – Karan Oct 22 '16 at 10:29

1 Answers1

0

The solution was here How to create an index from a variable in a dataframe

BaseTable$No1 <- as.numeric(factor(BaseTable$First))
BaseTable$No2 <- as.numeric(factor(BaseTable$Second))
BaseTable$No3 <- as.numeric(factor(BaseTable$Third))

for the loop:

combinations = c('First', 'Second', 'Third')
count = 1

for (i in combinations) {

  BaseTable[[paste("No", Count, sep="")]] <- match(BaseTable[[i]], unique(BaseTable[[i]])) # same order
  #BaseTable[[paste("No", Count, sep="")]] <- as.numeric(factor(BaseTable[[i]])) # new order
  count = count +1
}  
Community
  • 1
  • 1
timat
  • 1,480
  • 13
  • 17
  • Thanks, it worked, but I am still curious to know how to create dataframe columns with paste as i don't need to specify – Karan Oct 22 '16 at 08:33
  • BaseTable$No1 n BaseTable$No2. as i would be able to do this in a loop – Karan Oct 22 '16 at 08:35