1
votes

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
1
Please try to make a reproducible example so that it is easy for others to help you.Ronak Shah
Could you illustrate how the desired data.frame should look?Konrad
@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
This is a sample code,in the real code there is no such problem, but from the next time i will be carefullKaran

1 Answers

0
votes

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
}