gpt4 book ai didi

r - 在data.table r中按名称选择非连续列

转载 作者:行者123 更新时间:2023-12-01 21:38:30 24 4
gpt4 key购买 nike

我的磁盘上有数据库,我想使用 : 选择多个列,偶尔在 data.table 中使用列名。

以前的答案只包括使用索引进行列选择,这对我的情况来说是不可取的。

例子如下:

library(gapminder)
data(gapminder)
setDT(gapminder)

names(gapminder) # [1] "country" "continent" "year" "lifeExp" "pop" "gdpPercap"

# I would like to select columns from `country` to `year` and pop

gapminder[,country:year] # this one works



gapminder[,country:year + pop] # doesn't work
gapminder[,c(country:year,pop)] # doesn't work either

gapminder[,.SD, .SDcols = c(country:year,pop)] # doesn't work

我正在为这个问题挠头。我将不胜感激任何建议。

最佳答案

另一种选择:

gapminder[, c(.SD, .(pop=pop)), .SDcols=country:year] 

或者如果你有更多列,

cols <- setNames(c("pop", "lifeExp"), c("pop", "lifeExp"))
gapminder[, c(.SD, mget(cols)), .SDcols=country:year]

输出:

          country continent year      pop lifeExp
1: Afghanistan Asia 1952 8425333 28.801
2: Afghanistan Asia 1957 9240934 30.332
3: Afghanistan Asia 1962 10267083 31.997
4: Afghanistan Asia 1967 11537966 34.020
5: Afghanistan Asia 1972 13079460 36.088
---
1700: Zimbabwe Africa 1987 9216418 62.351
1701: Zimbabwe Africa 1992 10704340 60.377
1702: Zimbabwe Africa 1997 11404948 46.809
1703: Zimbabwe Africa 2002 11926563 39.989
1704: Zimbabwe Africa 2007 12311143 43.487

关于r - 在data.table r中按名称选择非连续列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61670413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com