maximusdooku maximusdooku - 1 month ago 15
R Question

How can I remove the file extensions from file Names and assign them to column names?

I have a dataframe A that has generic column names: V1 - V24. And I have 19 column names stored in a separate dataframe B that I need to assign to A. I want to:


  1. Remove .tif from the list of column names in dataframe B.

  2. The first 5 column names I am doing it manually. But rest of them should be read from the list B in the order it is given. Basically, V6 = bio_1, V7 = bio_10, etc.



Code:

library(dplyr)
B <- read.table('filenames.txt')
B$V1 <- as.character(B$V1)

B <- B %>%
mutate(col2 = strsplit(V1, "\\.")[[1]][1])


Also,

A <- read.csv('futuredata.csv',header=F)

A <- A %>%
rename(ID = V1, gauge = V2, lat = V3, lon = V4, area = V5) %>%


Data:

dput(A)

structure(list(V1 = 1:3, V2 = c(1094000L, 1100600L, 1096000L),
V3 = c(-71.506667, -71.215278, -71.658333), V4 = c(42.8575,
42.568056, 42.634167), V5 = c(442.888, 94.5346, 170.6802),
V6 = c(73.805907, 91.644231, 80.292398), V7 = c(190.198312,
205.201923, 196.80117), V8 = c(-50.635021, -26.259615, -43.94152
), V9 = c(1136.151899, 1118.826923, 1112.157895), V10 = c(113.563291,
114.557692, 112.538012), V11 = c(84.995781, 84.105769, 84.327485
), V12 = c(7.845992, 8.846154, 8), V13 = c(311.603376, 308.817308,
307.076023), V14 = c(264.763713, 255.980769, 262.22807),
V15 = c(281.383966, 255.980769, 269.672515), V16 = c(274.626582,
281.442308, 271.836257), V17 = c(121.006329, 115.336538,
122.830409), V18 = c(30.763713, 30.826923, 31), V19 = c(9281.014768,
8928.057692, 9269.432749), V20 = c(267.883966, 280.5, 274.900585
), V21 = c(-119.333333, -90.048077, -113.754386), V22 = c(387.2173,
370.548077, 388.654971), V23 = c(28.236287, -0.096154, 34.888889
), V24 = c(-37.721519, 205.201923, -13.134503)), .Names = c("V1",
"V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11",
"V12", "V13", "V14", "V15", "V16", "V17", "V18", "V19", "V20",
"V21", "V22", "V23", "V24"), row.names = c(NA, 3L), class = "data.frame")


dput(B)

structure(list(V1 = structure(1:19, .Label = c("bio_1.tif", "bio_10.tif",
"bio_11.tif", "bio_12.tif", "bio_13.tif", "bio_14.tif", "bio_15.tif",
"bio_16.tif", "bio_17.tif", "bio_18.tif", "bio_19.tif", "bio_2.tif",
"bio_3.tif", "bio_4.tif", "bio_5.tif", "bio_6.tif", "bio_7.tif",
"bio_8.tif", "bio_9.tif"), class = "factor")), .Names = "V1", class = "data.frame", row.names = c(NA,
-19L))


Problems:


  1. I am not getting the correct list after removing .tif.

  2. Not sure how to assign them to dataframe A


Answer

Maybe try this:

colnames(A) <- c("ID", "gauge", "lat", "lon", "area", tools::file_path_sans_ext(B$V1))

Here is dplyr way:

A <- 
  A %>% rename_(.dots = setNames(names(.), c("ID", "gauge","lat","lon","area",
                                             tools::file_path_sans_ext(B$V1))))
Comments