通过名称或索引引用列的功能 [英] A function for referring to columns by either name or index

查看:56
本文介绍了通过名称或索引引用列的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在一个向量中通过名称和索引来引用列.作为示例,我仅指定:

I would like to be able to refer to columns by name and index in one vector. As example I specify only:

我更改了原始向量的顺序,因为我希望顺序无关紧要.

I changed the order of the original vector as I want the order to not matter.

columns <- c(1:7, "j", 8, "i")

然后,我想检索索引1到9的名称,并将它们添加到向量中(在正确的位置).我有一个大致的想法,但是在编码方面我并没有走得太远:

I would then like to retrieve the names of the index 1 to 9 and add them to the vector (in the correct place). I have a general idea, but coding wise I am not getting very far:

library(data.table)
df <- fread(
"a b c d e f g h i j
1 2 3 4 5 6 7 8 9 10",
  header = TRUE
)

function(data, columns){
nums <- as.numeric(columns)
named_columns <- ?
nums <- nums[!is.na(nums)]
name_nums <- colnames(df)[nums]

all_columns <- setdiff(named_colums, name_nums)
# Order of the original vector?
column_names <- result
}

,然后将其返回到向量,以使结果为:

and then return it to the vector so that the outcome will be:

column_names <- c("a", ..., "j", "h", "i")

有人可以帮助我进一步发展吗?

Could anyone help me to get a bit further?

推荐答案

如果我理解您的问题,则希望传递包含列名和索引的向量,并且只想返回包含列索引的向量.那么以下内容应该有所帮助;

If I understand your question, you want to pass a vector which has column names and indices and you want to get back a vector with column indices only. Then the following should help;

df <- data.table::fread("a b c d e f g h i j
                         1 2 3 4 5 6 7 8 9 10",
                                               header = TRUE)
columns <- c(1:8, "i", 9, "j")


col2num <- function(df, columns){
              nums <- as.numeric(columns)
              nums[is.na(nums)] <- which(names(df)==columns[is.na(nums)])
              return(nums)
            }

col2num(df, columns)
#> Warning in col2num(df, columns): NAs introduced by coercion
#>  [1]  1  2  3  4  5  6  7  8  9  9 10

这篇关于通过名称或索引引用列的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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