使用paste语句创建data.frame列

时间:2016-10-22 07:07:37

标签: r dataframe

我有一个Current dataFrame,如:

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

现在,我想在data.frame中使用paste语句在此数据框中添加一列。我尝试使用assign()noquotes()进行此操作,但我创建了一个具有该名称的新变量。

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
}

我得到的输出是变量名BaseTable$no10[BaseTable$Perfect %in% Perfect] 其次,这里i是一个包含多个元素的向量,但使用paste语句时,它会将i[j]值显示为NA。 与First[1] = NA一样。

我想和输出一样:

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 个答案:

答案 0 :(得分:0)

解决方案在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))
循环

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
}