0

Assuming I have several data and I want to subset them respectively.

n = c(1, 1, 1) 
s = c(55, 56, 57) 
q = c(99, 100, 101)
df_1 = data.frame(n, s, q)
df_2 = data.frame(n, s, q)
df_3 = data.frame(n, s, q) # assume they are the same.

  n  s   q
1 1 55  99
2 1 56 100
3 1 57 101

Then I create a loop to call the file,

for (h in 1:3){    # for loop the file
  for (i in 1:1){  # i is for different values in column 'n'

    Result <- paste('ResultFile_',h,sep="")
    input <- paste('df_',h,sep="")

    Result <- subset(input,subset=n==i)[,c(2,3)]

DO SOMETHING HERE....

}
}

I expect that when column 'n' equaling to 1, I will get column S and Q. It will produce 3 result files to me.

But it comes with error message.

Error in subset.default(input, subset = n == i) : object 'n' not found

When I directly replace 'input' as 'df1' in this line subset(input,subset=n==i)[,c(2,3)], then it can work.

Why??

MlolM
  • 247
  • 3
  • 12
  • 3
    In your example `input` is a string that you make with `paste()` (verify with `class(input)`). `subset` needs you to pass in a data.frame. If you have a bunch of variables named `df_1`, `df_2`, `df_3` that's usually a sign that you are "going it wrong" in R. Your data.frames should be in a list to make this easier. See this question for better solutions: http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames – MrFlick Mar 07 '17 at 15:52

1 Answers1

2

It is possible to use the get function to pass your string to call the object. You can try something like this:

input <- get(paste("df_", h, sep = ""))

Now input is the same data frame as df_1, not a string "df_1".

By the way, if you want to apply a function through several data frames, it is possible to create a list of all data frame, then use lapply to apply the function. For example, if you want to subset all data frames if s == 56.

data_list <- list(df_1, df_2, df_3)
data_list2 <- lapply(data_list, subset, subset = s == 56)

All the resulting data frames are now stored in data_list2.

www
  • 35,154
  • 12
  • 33
  • 61
  • Thanks for the `get` method, it works fine, @ycw ,but how about creating several `ResultFile_` file at the same time? (In my case is 3 result files). – MlolM Mar 07 '17 at 16:21
  • 1
    You can use `mget` to create multiple datasets in a `list` – akrun Mar 07 '17 at 16:28
  • 1
    @BigSecrect, You can try the `assign` function. For example, after the `Result` data frame is created using `subset`, add the following code `assign(paste('ResultFile_', h, sep=""), Result)`. – www Mar 07 '17 at 16:40