r数据表按列的第二列列表划分列

时间:2016-06-14 03:54:24

标签: r data.table

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

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元素中的值,但未成功。两个在下面;既不起作用。

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))]

2 个答案:

答案 0 :(得分:6)

我们需要使用listvector转换为[[,然后使用list获取mget中每个向量的值,使用{ {1}}划分(Map)每个/值的相应列,并将其分配给向量(list)。

listRatio[[1]]

注意:正如评论中提到的@Frank,最好创建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 个变量名称,而不是vector

答案 1 :(得分:2)

使用data.frame函数

dt <- data.frame(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(dt[,c("V1", "V2", "V3")])
list2 <- list(dt[,c("V2", "V4", "V5")])
dt$rat3 <- dt$rat2 <- dt$rat1 <- ""
dt[, c("rat1","rat2","rat3")] <- unlist(list1)/unlist(list2)

         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