使用.I表示法的data.table的行方式操作[重复](rowwise operations with data.table using the .I notation [duplicate])

编程入门 行业动态 更新时间:2024-10-24 23:28:28
使用.I表示法的data.table的行方式操作[重复](rowwise operations with data.table using the .I notation [duplicate])

这个问题在这里已有答案:

计算行数最多 3个答案

我遇到了一个data.table行为怪癖,我想在那里进行逐行操作,但除非我先提供一个虚拟变量,否则不能这样做。 是否有一步到位的方法来做到以下几点?

# I will calculate global vectorize max/min when going by `.I` dt <- data.table(x=runif(10), y=runif(10)) dt[, c("max","min"):=list(max(x,y), min(x,y)), by =.I] dt # note max/min are the same across rows x y max min 1: 0.9311597 0.89425124 0.9907917 0.06315146 2: 0.8007628 0.59832764 0.9907917 0.06315146 3: 0.6626013 0.90871193 0.9907917 0.06315146 4: 0.5857697 0.18239589 0.9907917 0.06315146 # creating a rowid will do the trick # however, this requires three steps (create, calc, delete) dt <- data.table(x=runif(10), y=runif(10)) dt[, rowid:=1:.N] dt[, c("max","min"):=list(max(x,y), min(x,y)), by=rowid] dt # note each row is correctly calculated x y rowid max min 1: 0.02321296 0.751962427 1 0.7519624 0.023212956 2: 0.93987266 0.504301816 2 0.9398727 0.504301816 3: 0.99621226 0.847503323 3 0.9962123 0.847503323 4: 0.66251070 0.003959591 4 0.6625107 0.003959591

```

This question already has an answer here:

Calculate row-wise maximum 3 answers

I've come across a data.table behavioral quirk where I wish to perform rowwise operations but cannot do so unless I first provide a dummy variable. Is there a one-step way to do the following?

# I will calculate global vectorize max/min when going by `.I` dt <- data.table(x=runif(10), y=runif(10)) dt[, c("max","min"):=list(max(x,y), min(x,y)), by =.I] dt # note max/min are the same across rows x y max min 1: 0.9311597 0.89425124 0.9907917 0.06315146 2: 0.8007628 0.59832764 0.9907917 0.06315146 3: 0.6626013 0.90871193 0.9907917 0.06315146 4: 0.5857697 0.18239589 0.9907917 0.06315146 # creating a rowid will do the trick # however, this requires three steps (create, calc, delete) dt <- data.table(x=runif(10), y=runif(10)) dt[, rowid:=1:.N] dt[, c("max","min"):=list(max(x,y), min(x,y)), by=rowid] dt # note each row is correctly calculated x y rowid max min 1: 0.02321296 0.751962427 1 0.7519624 0.023212956 2: 0.93987266 0.504301816 2 0.9398727 0.504301816 3: 0.99621226 0.847503323 3 0.9962123 0.847503323 4: 0.66251070 0.003959591 4 0.6625107 0.003959591

```

最满意答案

这可以使用pmax和pmin来完成

library(data.table) dt[, c("max","min"):=list(pmax(x,y), pmin(x,y))]

this can be accomplished using pmax and pmin

library(data.table) dt[, c("max","min"):=list(pmax(x,y), pmin(x,y))]

更多推荐

本文发布于:2023-08-03 13:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作   方式   table   data   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!