使用data.table中的字符串以列表方式命名列 [英] naming a column in a list manner with string in data.table

查看:57
本文介绍了使用data.table中的字符串以列表方式命名列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,无法在data.table中正确解决。我有以下数据:

I have a problem that I don't manage to solve properly in data.table. I have the following data:

plouf <- data.table(  ID = rep(LETTERS[1:10],each = 10) )
plouf[,c(paste0("X",1:10)) := lapply(1:10,function(x){sample(10,100,replace = T)})]

有两件事阻碍了我的时间:

There are two things that block me time to time:

 col <- "X1"
 plouf[get(col) > 5, .(col = get(col)[1]) ,by = ID]
    ID col
 1:  A   7
 2:  B   7
 3:  C   9
 4:  D   6
 5:  E   8
 6:  F   7
 7:  G   6
 8:  H   7
 9:  I   6
10:  J   7

该列名为 col而不是 X1。我尝试了 eval get ,却没有。

The column is named "col" instead of "X1". I tried with eval, get, didn't get it.

和同一种类:

 col <- 1
 plouf[get(paste0("X",col)) > 5, .(paste0("X",col) = get(paste0("X",col))[1]) ,by = ID]

Error: unexpected '=' in "plouf[get(paste0("X",col)) > 5, .(paste0("X",col) ="

我尝试从命名列表时使用粘贴

 plouf[get(paste0("X",col)) > 5,setNames( get(paste0("X",col))[1],paste0("X",col)) ,by = ID]

    ID V1
 1:  A  7
 2:  B  7
 3:  C  9
 4:  D  6
 5:  E  8
 6:  F  7
 7:  G  6
 8:  H  7
 9:  I  6
10:  J  7

但这不是理想的结果。有人可以解释一下它的工作原理吗?

but it is not the desired result. Could someone explain me how it works ?

推荐答案

我们可以使用 setNames

plouf[get(col) > 5, setNames(list(get(col)[1]), col) ,by = ID]

或另一个选项是 setnames 得到结果后

or another option is setnames after getting the result

setnames(plouf[get(col) > 5, .(get(col)[1]) ,by = ID], 'V1', col)[]
#   ID X1
#1:  A  8
#2:  B  7
#3:  C  6
#4:  D 10
#5:  F  9
#6:  G  8
#7:  H 10
#8:  I  6
#9:  J  8






如果我们使用的是 dplyr ,则选项为

library(dplyr)
plouf %>%
   filter_at(col, any_vars(.>5)) %>%
   group_by(ID) %>% 
   summarise_at(col, first)
# A tibble: 9 x 2
#  ID       X1
#  <chr> <int>
#1 A         8
#2 B         7
#3 C         6
#4 D        10
#5 F         9
#6 G         8
#7 H        10
#8 I         6
#9 J         8

或者使用:= sym 来自 rlang

plouf %>% 
    filter(!! rlang::sym(col) > 5) %>%
    group_by(ID) %>% 
    summarise(!! col := first(!!rlang::sym(col)))

这篇关于使用data.table中的字符串以列表方式命名列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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