r数据表将列的列表除以列的第二列表 [英] r data table divide list of columns by a second list of columns

查看:715
本文介绍了r数据表将列的列表除以列的第二列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本生成一个数据表,其中包含一些列,我想要除以一些其他列,并将结果存储在新的列中。这里有一个例子。

I have script that generates a data table with some columns I want to divide by some other columns and store the results in new columns. Here's an example.

library(data.table)
dt <- data.table(V1 = c( 5.553465,  4.989168,  2.563682,  6.987971, 19.220936),
                 V2 = c(4.248335, 19.768138,  3.840026, 17.411003, 17.939368),
                 V3 = c(9.683953, 15.344424, 11.729091,  7.534210,  5.404000),
                 V4 = c(5.949093,  4.553023,  9.765656, 11.211069,  4.085964),
                 V5 = c(11.814671,  5.460138,  2.492230,  1.48792,  8.164280))

list1 <- list(c("V1", "V2", "V3"))
list2 <- list(c("V2", "V4", "V5"))
listRatio <- list(c("rat1","rat2","rat3"))



将list1元素中的值除以list2元素中的值的方法未成功。两个在下面;都不工作。

I have tried a variety of approaches to dividing the values in the list1 elements by the values in the list2 elements, unsuccessfully. Two are below; neither works.

dt[, (listRatio) := list1/list2]
dt[, c("rat1","rat2","rat3") := mapply(dt, function(x,y) x / y, x = c(V1, V2, V3),  y = c(V2, V4, V5))]


推荐答案

我们需要转换通过使用 [[],然后获取每个向量的值在向量 code>列表使用 mget ,使用映射 $ c> / )每个列表值的相应列并将其分配给向量( listRatio [[ 1]] )。

We need to convert the list to vector by using [[ and then get the values of each vector in a list with mget, use Map to divide (/) the corresponding columns of each of the list values and assign it to the vector (listRatio[[1]]).

dt[, (listRatio[[1]]) := Map(`/`, mget(list1[[1]]), mget(list2[[1]]))]
dt
#          V1        V2        V3        V4        V5      rat1      rat2      rat3
#1:  5.553465  4.248335  9.683953  5.949093 11.814671 1.3072098 0.7141147 0.8196549
#2:  4.989168 19.768138 15.344424  4.553023  5.460138 0.2523843 4.3417611 2.8102630
#3:  2.563682  3.840026 11.729091  9.765656  2.492230 0.6676210 0.3932174 4.7062635
#4:  6.987971 17.411003  7.534210 11.211069  1.487920 0.4013537 1.5530190 5.0635854
#5: 19.220936 17.939368  5.404000  4.085964  8.164280 1.0714389 4.3904861 0.6619077

请注意:作为@Frank在评论中提到,最好创建一个向量的变量名称而不是列表

NOTE: As @Frank mentioned in the comments, it is better to create a vector of variables names and not a list.

这篇关于r数据表将列的列表除以列的第二列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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