简体   繁体   中英

object not found Error when subsetting using r

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??

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM