【问题标题】:Is there a function in R to create a new column in a dataframe from a function?R中是否有一个函数可以从函数在数据框中创建一个新列?
【发布时间】:2020-09-08 20:10:42
【问题描述】:
df <- data.frame(cod = c(1,1,2,1,2,2), 
                 nom = c("banana", "banana", "orange", "banana", "orange", "orange"), 
                 val = rnorm(6, 0.06, 0.01))


df <- as.data.table(df)

categol = function(base, col){

      colss = c(paste(col,'_1',sep=''),paste(col,'_2',sep=''))
      base[, colss[1] := 0]
      base[, colss[2] := 0]
      base[as.name(col) == 1, colss[1] := 1]
      base[as.name(col) == 2, colss[2] := 1]

}
categol(df, 'cod')

很遗憾,这不起作用。

【问题讨论】:

  • Eder,请做一个最小的可重现示例。见stackoverflow.com/questions/5963269。您必须包含一些示例输入数据;通常 4-10 行就足够了。包括您希望输出看起来像的示例。不要包含图像或指向外部数据源的链接。我们想帮助您,但您必须与我们合作。
  • 也许你需要在函数结束时return(base)?并分配结果? df &lt;- categol(df, 'cod')?正如大卫所说,如果您更清楚地说明目标是什么,那么提供帮助会更容易。

标签: r function data.table


【解决方案1】:

如果您想在data.table 中执行此操作,您可以使用get 从字符串名称中获取列值。

library(data.table)

categol = function(base, col){
   #Create column names
   cols = paste0(col,'_', 1:2)
   #Initialize them to 0
   base[, (cols) := 0]
   #If col is 1 assign 1 to cols[1]
   base[get(col) == 1, (cols[1]) := 1]
   #If col is 2 assign 1 to cols[2]
   base[get(col) == 2, (cols[2]) := 1] 
   #Return the data
   return(base)
}

然后拨打categol

out <- categol(df, 'cod')
out
#   cod    nom        val cod_1 cod_2
#1:   1 banana 0.04475522     1     0
#2:   1 banana 0.03908076     1     0
#3:   2 orange 0.05077533     0     1
#4:   1 banana 0.05125148     1     0
#5:   2 orange 0.04395974     0     1
#6:   2 orange 0.05967578     0     1

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 2021-11-14
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多