簡體   English   中英

R:在R數據表中的特定位置插入一列

[英]R: Insert a column at a specific place in R data table

我有以下數據表

      user_id user_system_days event total_pics 
[1,] 21196680             0     0         124   
[2,] 21197699             0     0           4   
[3,] 21197861             0     0          14   
[4,] 21198820             1     0          21   
[5,] 21199601             0     0           3   
[6,] 21203847             0     0           1   

基於列事件中的值,我想在數據表中插入一列,我的方法是編寫一個函數,然后使用該函數返回一個值。

opposite_event  <- function(x) {
  y <- 1
  if (x == 1) 
    y <- 0
  return (y)
}

我調用函數如下:

dt[,op_event:=opposite_event(dt$event)]

這實際上添加了列,但值是錯誤的:

      user_id user_system_days event total_pics op_event
[1,] 21196680             0     0         124      0
[2,] 21197699             0     0           4      0
[3,] 21197861             0     0          14      0
[4,] 21198820             1     0          21      0
[5,] 21199601             0     0           3      0
[6,] 21203847             0     0           1      0

根據我的函數,如果dt$event值為1則返回值應為0 ,如果dt$event為0,則返回值應為1 Plus我不知道如何將列插入特定位置柱。

if沒有矢量化,則將其替換為y <- ifelse(x == 0, 1, 0)

在我看來,你真的不需要自定義功能:

dt[,op_event := ifelse(event == 0, 1, 0)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM