A function for referring to columns by either name or index

℡╲_俬逩灬. 提交于 2019-12-11 02:13:54

问题


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

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

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/57101282/a-function-for-referring-to-columns-by-either-name-or-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!