Extraer la extensión del archivo de la ruta del archivo
¿Cómo puedo extraer la extensión de un archivo dada una ruta de archivo como un carácter? Sé que puedo hacer esto a través de la expresión regular regexpr("\\.([[:alnum:]]+)$", x)
, pero me pregunto si hay una función incorporada para lidiar con esto?
5 answers
Este es el tipo de cosas que se encuentran fácilmente con R basic tools. Por ejemplo:??camino.
De todos modos, cargue el paquete tools
y lea ?file_ext
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-15 16:23:50
El regexpr anterior falla si la extensión contiene no alnum (véase, por ejemplo, https://en.wikipedia.org/wiki/List_of_filename_extensions ) Como altenativo se puede utilizar la siguiente función:
getFileNameExtension <- function (fn) {
# remove a path
splitted <- strsplit(x=fn, split='/')[[1]]
# or use .Platform$file.sep in stead of '/'
fn <- splitted [length(splitted)]
ext <- ''
splitted <- strsplit(x=fn, split='\\.')[[1]]
l <-length (splitted)
if (l > 1 && sum(splitted[1:(l-1)] != '')) ext <-splitted [l]
# the extention must be the suffix of a non-empty name
ext
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-02 17:20:22
Permítanme ampliar un poco la gran respuesta de https://stackoverflow.com/users/680068/zx8754
Aquí está el fragmento de código simple
# 1. Load library 'tools'
library("tools")
# 2. Get extension for file 'test.txt'
file_ext("test.txt")
El resultado debe ser 'txt'.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-04 20:53:09
Esta función utiliza tuberías:
library(magrittr)
file_ext <- function(f_name) {
f_name %>%
strsplit(".", fixed = TRUE) %>%
unlist %>%
extract(2)
}
file_ext("test.txt")
# [1] "txt"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-01 11:25:06
Función simple sin paquete para cargar:
getExtension <- function(file){
ex <- strsplit(basename(file), split="\\.")[[1]]
return(ex[-1])
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-26 07:06:10