I tried to create an easier way to refer to columns with the function below, by allowing both indexes and names. See also link.
So this one works:
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
And this one works too:
col2name <- function(df, columns){
nums <- as.numeric(columns)
nums[is.na(nums)] <- which(names(df)==columns[is.na(nums)])
return(names(df)[nums])
}
col2name(df, columns)
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "i" "j"
Warning message:
In col2name(df, columns) : NAs introduced by coercion
But when I do the following, it no longer works:
columns <- c(1:7, "j", 8, "i")
col2name <- function(df, columns){
nums <- as.numeric(columns)
nums[is.na(nums)] <- which(names(df)==columns[is.na(nums)])
return(names(df)[nums])
}
col2name(df, columns)
Error in nums[is.na(nums)] <- which(names(df) == columns[is.na(nums)]) :
replacement has length zero
Also, this one does not work:
columns <- c("a", "j", 8, "i")
col2name <- function(df, columns){
nums <- as.numeric(columns)
nums[is.na(nums)] <- which(names(df)==columns[is.na(nums)])
return(names(df)[nums])
}
col2name(df, columns)
[1] "a" "i" "h" "a"
How can I fix this?