r - 使用 data.table 和 lapply 的变量中的列名
问题描述
我有类似这样的数据:
set.seed(1)
testing1 <- data.table(type=c("stock","stock","bond","bond"),a=rnorm(4),b=rnorm(4),c=rnorm(4),d=rnorm(4),e=rnorm(4))
type a b c d e
1: stock -0.6264538 0.3295078 0.5757814 -0.62124058 -0.01619026
2: stock 0.1836433 -0.8204684 -0.3053884 -2.21469989 0.94383621
3: bond -0.8356286 0.4874291 1.5117812 1.12493092 0.82122120
4: bond 1.5952808 0.7383247 0.3898432 -0.04493361 0.59390132
这正是我想要的:
result1 <- testing1[,c(list(type=type),lapply(.SD, `-`, a)), .SDcols = b:e]
type b c d e
1: stock 0.9559616 1.2022352 0.00521323 0.6102635
2: stock -1.0041117 -0.4890317 -2.39834321 0.7601929
3: bond 1.3230577 2.3474098 1.96055953 1.6568498
4: bond -0.8569561 -1.2054376 -1.64021441 -1.0013795
问题是该列a
是动态命名的。我想做这样的事情:
cn <- "a"
result2 <- testing1[,c(list(type=type), lapply(.SD, `-`, get(cn))), .SDcols = b:e]
但我收到错误消息:Error in FUN(X[[i]], ...) : non-numeric argument to binary operator
。
任何想法将不胜感激。谢谢。
解决方案
我们可以利用[[
从“testing1”中提取列。此处.SD
不起作用,因为未指定该列.SDcols
testing1[,c(list(type=type),lapply(.SD, `-`, testing1[[cn]])), .SDcols = b:e]
# type b c d e
#1: stock 0.9559616 1.2022352 0.00521323 0.6102635
#2: stock -1.0041117 -0.4890317 -2.39834321 0.7601929
#3: bond 1.3230577 2.3474098 1.96055953 1.6568498
#4: bond -0.8569561 -1.2054376 -1.64021441 -1.0013795
如果我们使用get
,请确保环境与 with 相同lapply
,环境来自.SD
没有列“a”。而是使用Map
testing1[, Map(`-`, .SD, list(get(cn))), .SDcols = b:e]
推荐阅读
- .htaccess - 如何为 Google Search Console 网站移动工具正确实施 301 重定向?
- mysql - MariaDB/mysql SQL查询问题:我想根据另一列的组值对一列进行部分总和
- git - 删除 git:'credential-manager' 不是 git 命令。来自 Mac
- python - 我尝试使用 ZIP 解压缩 3 个不同的列表。但我得到了价值混合和报价
- c# - HtmlAgilityPack 返回编码错误的文本
- javascript - 如何从 BehaviorSubject 获取数组的最后一项
- terraform - Terraform:仅当变量匹配某些值时才创建块
- angular - StoryBook Angular - 错误!=> 无法获取 Angular cli webpack 配置
- python - Django ckeditor - 默认情况下如何创建上传图像的缩略图
- r - 按列名(而不是按列值)合并(组合)行