0

I need to take a basename from a file path and insert it into a variable so I can access a column in a dataframe. I have created some sample data to illustrate what I am trying to accomplish.

Create some sample data:

library(raster)    
## Create a matrix with random data & use image()
xy = matrix(rnorm(400),20,20)
image(xy)

# Turn the matrix into a raster
rast = raster(xy)
# Give it lat/lon coords for 36-37°E, 3-2°S
extent(rast) = c(36,37,-3,-2)
# ... and assign a projection
projection(rast) = CRS("+proj=longlat +datum=WGS84")
plot(rast)

# Write to disk:
writeRaster(rast, "C:/temp/12345.tif", format = "tif")

Create a path to raster

path = 'C:/temp/12345.asc

Create a raster object:

r = raster(file)

Sample random locations in raster and report values in a dataframe

df = data.frame(sampleRandom(r, size=1000, cells=TRUE, sp=TRUE))

Now I need to automate the insertion of the basename into a variable so that it looks like:

test = df$X12345

This is my unsuccessful attempt at inserting the basename into the test variable:

require(tools)
name = basename(file_path_sans_ext(path))
test2 = paste('df$', 'X', name, sep = '')

>test2
[1] "df$X12345"

This method seems to create a the correct character "df$X12345", although I cannot access the dataframe by calling test2. How can I construct a series of characters into a functioning variable so that I can access the particular dataframe column?

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Borealis
  • 8,044
  • 17
  • 64
  • 112

2 Answers2

1

Maybe you are looking for parse and eval:

df <- data.frame(a = 1, b = 2)
test2 <- "df$b"
eval(parse(text = test2))
# [1] 2
lukeA
  • 53,097
  • 5
  • 97
  • 100
0

test = df[,paste0('X', name)]

Is this what you're looking for?

loard
  • 93
  • 7