使用data.table在两列之间交换值 [英] Swapping values between two columns using data.table

查看:87
本文介绍了使用data.table在两列之间交换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将此问题翻译成 data.table 解决方案。 (为简单起见,我将使用相同的数据集)

V2 == b 时,我想在<$ c之间交换列$ c> V1<-V3 。

I have been breaking my head over translating this question to a data.table solution. (to keep it simple I'll use the same data set)
When V2 == "b I want to swap the columns between V1 <-> V3.

dt <- data.table(V1=c(1,2,4), V2=c("a","a","b"), V3=c(2,3,1))
#V1 V2 V3
#1:  1  a  2
#2:  2  a  3
#3:  4  b  1

下面的代码将是 data.frame 的有效解决方案,但是由于我使用<$感到沮丧,这给了我很多c $ c> data.table 没有意识到,我现在决定为data.table找到解决方案。

The code below would be the working solution for data.frame, however because of the amount of frustration this has given me because I was using a data.table without realising I'm now determined to find a solution for data.table.

dt <- data.table(V1=c(1,2,4), V2=c("a","a","b"), V3=c(2,3,1))
df <- as.data.frame(dt)
df[df$V2 == "b", c("V1", "V3")] <- df[df$V2 == "b", c("V3", "V1")] 
#  V1 V2 V3
#1  1  a  2
#2  2  a  3
#3  1  b  4

我尝试写 lapply 函数遍历我的目标交换列表,特里d将问题缩小为仅替换一个值,尝试以不同的方式调用列名,但都没有成功。

这是我设法获得的最接近的尝试:

I have tried writing a lapply function looping through my target swapping list, tried to narrow down the problem to only replace one value, attempted to call the column names in different ways but all without success.
This was the closest attempt I've managed to get:

> dt[dt$V2 == "b", c("V1", "V3")] <- dt[dt$V2 == "b", c(V3, V1)]
#Warning messages:
#1: In `[<-.data.table`(`*tmp*`, dt$V2 == "b", c("V1", "V3"), value = c(1,  :
#  Supplied 2 items to be assigned to 1 items of column 'V1' (1 unused)
#2: In `[<-.data.table`(`*tmp*`, dt$V2 == "b", c("V1", "V3"), value = c(1,  :
#  Supplied 2 items to be assigned to 1 items of column 'V3' (1 unused)

我们如何获得data.table解决方案?

How can we get the data.table solution?

推荐答案

我们可以尝试

dt[V2=="b", c("V3", "V1") := .(V1, V3)]

这篇关于使用data.table在两列之间交换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆