如何将数据表中的多个列设置为同一数据表中不同列的值? [英] How to set multiple columns in a data table to values from different columns in the same data table?
本文介绍了如何将数据表中的多个列设置为同一数据表中不同列的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个6列的数据帧,我想设置col 1:3为col 4:6中的值(合并时会出现很多)。使用数据框很容易:
set.seed(1)
df< - data.frame样品(1:100,30),ncol = 6))
df
#X1 X2 X3 X4 X5 X6
#1 27 86 19 43 75 29
#2 37 97 16 88 17 1
#3 57 62 61 83 51 28
#4 89 58 34 32 10 81
#5 20 6 67 63 21 25
df [ ,1:3]< - df [,4:6]#非常非常简单...
df
#X1 X2 X3 X4 X5 X6
#1 43 75 29 43 75 29
#2 88 17 1 88 17 1
#3 83 51 28 83 51 28
#4 32 10 81 32 10 81
#5 63 21 25 63 21 25 $ data.tables不是这么多:
pre> library(data.table)
dt< - data.table(df)
dt [,1:3,with = F] [,4:6,with = F]
##错误在`[< - 。data.table`(`* tmp *`,,1:3,with = F,value = list(X4 = c(43L,:unused argument(with = F)
一个简单的转换:
dt [,names(dt)[1:3]:= dt [,4:6,with = F]]#非常非常复杂...
dt
#X1 X2 X3 X4 X5 X6
#1:43 75 29 43 75 29
#2:88 17 1 88 17 1
#3:83 51 28 83 51 28
#4:32 10 81 32 10 81
#5:63 21 25 63 21 25
问题是:有一种更简单的方法来将数据表中的一组列分配给
您可以使用:=
/ code>运算符和与= FALSE
:
code> dt [,1:3:= dt [,4:6,with = FALSE],with = FALSE]
> dt
X1 X2 X3 X4 X5 X6
1:43 75 29 43 75 29
2:88 17 1 88 17 1
3:83 51 28 83 51 28
4:32 10 81 32 10 81
5:63 21 25 63 21 25
Suppose I have a data frame with 6 columns, and I want to set col 1:3 to the values in col 4:6 (this comes up a lot when merging). With data frames it's easy:
set.seed(1)
df <- data.frame(matrix(sample(1:100,30),ncol=6))
df
# X1 X2 X3 X4 X5 X6
# 1 27 86 19 43 75 29
# 2 37 97 16 88 17 1
# 3 57 62 61 83 51 28
# 4 89 58 34 32 10 81
# 5 20 6 67 63 21 25
df[,1:3] <- df[,4:6] # very, very straightforward...
df
# X1 X2 X3 X4 X5 X6
# 1 43 75 29 43 75 29
# 2 88 17 1 88 17 1
# 3 83 51 28 83 51 28
# 4 32 10 81 32 10 81
# 5 63 21 25 63 21 25
With data.tables, not so much:
library(data.table)
dt <- data.table(df)
dt[,1:3,with=F] <- dt[,4:6,with=F]
## Error in `[<-.data.table`(`*tmp*`, , 1:3, with = F, value = list(X4 = c(43L, : unused argument (with = F)
This works, but seems extremely complicated for such a simple transformation:
dt[, names(dt)[1:3]:=dt[,4:6,with=F]] # very, very complicated...
dt
# X1 X2 X3 X4 X5 X6
# 1: 43 75 29 43 75 29
# 2: 88 17 1 88 17 1
# 3: 83 51 28 83 51 28
# 4: 32 10 81 32 10 81
# 5: 63 21 25 63 21 25
The question is: is there a simpler way to assign one set of columns in a data table to the values from another set of columns in the same data table?
解决方案
You can use the :=
operator and a with=FALSE
in each data.table:
dt[, 1:3 := dt[, 4:6, with=FALSE], with=FALSE]
> dt
X1 X2 X3 X4 X5 X6
1: 43 75 29 43 75 29
2: 88 17 1 88 17 1
3: 83 51 28 83 51 28
4: 32 10 81 32 10 81
5: 63 21 25 63 21 25
这篇关于如何将数据表中的多个列设置为同一数据表中不同列的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文