r create and address variable in for loop

前端 未结 1 476
轮回少年
轮回少年 2021-01-28 20:27

I have multiple csv-files in one folder. I want to load each csv-file in this folder into one separate data frame. Next, I want to extract certain elements from this data frame

相关标签:
1条回答
  • 2021-01-28 20:54

    This is not something you should probably be using assign for in the first place. Working with a bunch of different data.frames in R is a mess, but working with a list of data.frames is much easier. Try reading your data with

    group_1<-list.files()
    mferg <- lapply(group_1, function(filename) { 
        read.csv(filename,header=FALSE,sep=";",quote="",dec=",",col.names=1:90))
    })
    

    and you get each each value with mferg[[1]], mferg[[1]], etc. And then you can create a list of extractions with

    mferg_matrix <- lapply(mferg, function(x) x[1:5, 1:10])
    

    This is the more R-like way to do things.

    But technically you can use get to retrieve values like you use assign to create them. For example

    assign(paste0("mferg_matrix_",i),get(paste0("mferg_",i))[1:5,1:10])
    

    but again, this is probably not a smart strategy in the long run.

    0 讨论(0)
提交回复
热议问题