Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.8k views
in Technique[技术] by (71.8m points)

how to load() and view() a function argument [i.e. function(x) ] in R

I'm having trouble with load and view. I want to write functions that will allow me to do a whole lot of things by just naming what will be a dataframe

# example dataset
n <- 3
dat <- data.frame(
  c1=sample(1:5, n, replace=TRUE),
  c2=sample(1:5, n, replace=TRUE)   )
save(dat, file = "dat.rda")
# my function to load and view a dataframe with a single call
jtest <- function(x) {
load(    paste0(      x,".Rda")    )
View(    paste0(      x,".Rda")    )
}

jtest("dat")

My desired output would be that it loads up the dataframe dat

  c1 c2
1  1  3
2  1  5
3  5  5

Instead, when I run jtest("dat") it opens something with the same icon as a dataframe named paste0(x, ".Rda"), one column named V1, one row named "1", and a cell value of dat.Rda: V1 1 dat.Rda

I've looked at a couple of options, trying to wrap variously in as.name() or use assign() but I must be really thick because I'm not getting it!

Ref: Error in object[seq_len(ile)] : object of type 'symbol' is not subsettable


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

View needs a R object, you are passing character value to it. You can use get to get R object from it's name.

jtest <- function(x) {
  load(paste0(x,".Rda"))
  View(get(x), title = x)
}

jtest("dat")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...