Looping a series of variables in R while doing a cbind()

I have already read a dataset in R though read.csv and after doing some calculations created the following 10 variables of similar names, PI_1,PI_2,.....,PI_10

Now I combine the newly formed variables with my existing dataset (TempData).

x<-cbind(TempData,PI_1,PI_2,PI_3,PI_4,PI_5,PI_6,PI_7,PI_8,PI_9,PI_10)

Is there any smarter way of doing this (maybe by a loop). Any help is greatly appreciated

Upvotes: 0

Views: 165

Answers (1)

akrun
akrun

Reputation: 887991

Assuming that the files are in the working directory and all of them starts with PI_ followed by some digits \\d+, we can use list.files with pattern argument in case there are other files also in the directory. To check the working directory, use getwd()

  files <- list.files(pattern='^PI_\\d+')

This will give the file names. Now, we can use lapply and read those files in the list using read.table. Once, we are done with that part, use do.call(cbind to bind all the dataset columns together.

  res <- do.call(cbind,lapply(files, function(x) 
                     read.table(x, header=TRUE)))

Update

I guess you need to create 10 variables based on some PI. In the code that was provided in the comments, PI seems to be an object with some value inside it. Here, I am creating PI as the value as it is not clear. I created a dummy dataset.

  TempData[paste0('PI_', 1:10)] <- Map(function(x,y) c('', 'PI')[(x==y)+1],
                                  1:10, list(TempData$Concept)) 

   head(TempData,3)
  #  Concept        Val PI_1 PI_2 PI_3 PI_4 PI_5 PI_6 PI_7 PI_8 PI_9 PI_10
  #1      10 -0.4304691                                                 PI
  #2      10 -0.2572694                                                 PI
  #3       3 -1.7631631             PI                                    

You could use write.table to save the results

data

set.seed(42)
dat <- data.frame(Concept=sample(1:10,50, replace=TRUE), Val=rnorm(50))
write.csv(dat, 'Concept.csv', row.names=FALSE,quote=FALSE)
TempData <- read.csv('Concept.csv')
str(TempData)
#'data.frame':  50 obs. of  2 variables:
# $ Concept: int  10 10 3 9 7 6 8 2 7 8 ...
# $ Val    : num  -0.43 -0.257 -1.763 0.46 -0.64 ...

Upvotes: 1

Related Questions