【问题标题】:Creating a data.frame Column with paste statement使用粘贴语句创建 data.frame 列
【发布时间】:2016-10-22 07:07:37
【问题描述】:

我有一个 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 是一个具有多个元素的向量,但是使用粘贴语句,它将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

【问题讨论】:

  • 请尝试制作reproducible example,以便他人帮助您。
  • 您能否说明所需的data.frame 的外观?
  • @Karan,您应该避免使用大写字母.. 并在发布代码之前测试您的代码,因为这不起作用:For 而不是 forCombinations 而不是 @987654336 @.
  • 这是一个示例代码,在实际代码中没有这样的问题,但下次我会小心的

标签: r dataframe


【解决方案1】:

解决方案在这里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
}  

【讨论】:

  • 谢谢,它成功了,但我仍然很想知道如何使用粘贴创建数据框列,因为我不需要指定
  • BaseTable$No1 n BaseTable$No2。因为我可以循环执行此操作
  • 好的,谢谢。
  • @Karan 不客气,可以标记为已解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 2020-10-01
  • 1970-01-01
相关资源
最近更新 更多