将列列表除以第二列列表 [英] Divide list of columns by a second list of columns
问题描述
我有一个脚本,该脚本会生成一个 data.table
,其中包含我要除以其他某些列的某些列,并将结果存储在新列中。这是一个例子。
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))]
推荐答案
我们需要转换 list
转换为 vector
,方法是使用 [[,然后获取
list
和 mget
,使用 Map
进行除法( /
)每个 list
值的对应列,并将其分配给向量( 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
.
这篇关于将列列表除以第二列列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!